网站A通过jqeury要求网站B的api接口时,会提示跨域问题,这时候有2种跨域处理。
一是:做事器端设置跨域问题,比如后端是php开拓
header("Access-Control-Allow-Origin: ");header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, X-Token");header("Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH");header("Access-Control-Allow-Credentials: true");
二是:在nginx设置跨域问题配置。即本文重点先容的方法
在nginx.conf文件http里配置
add_header Access-Control-Allow-Origin ; add_header Access-Control-Allow-Credentials true; add_header Access-Control-Allow-Methods GET,POST,OPTIONS; add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
2、在(有多个项目配置的)详细的项目配置里location /里配置
if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin ; add_header Access-Control-Allow-Methods GET,POST,OPTIONS; add_header Access-Control-Allow-Credentials true; add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type; return 204;}
末了,欢迎大家留言补充,谈论~~~