浏览器同源策略:

  • 同一个协议
  • 同一个端口
  • 同一个域名

不满足同源策略,浏览器就视为是跨域请求 **


处理方式有两种

  • nginx
  • web server

    nginx:

    ```nginx location / {
    1. proxy_set_header Host $host:$server_port;
    2. add_header 'Access-Control-Allow-Credentials' 'true';
    3. add_header Access-Control-Allow-Origin "$http_origin";
    4. add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    5. if ($request_method = 'OPTIONS') {
    6. return 204;
    7. }
    8. add_header Cache-Control no-cache;
    9. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    10. proxy_pass 代理地址

}

  1. 或只给 `options` 请求加速
  2. ```nginx
  3. if ($request_method = OPTIONS ) {
  4. add_header Access-Control-Allow-Origin "*";
  5. add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
  6. add_header Access-Control-Max-Age "3600";
  7. add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization";
  8. add_header Content-Type text/plain;
  9. add_header 'Access-Control-Allow-Credentials' 'true';
  10. return 200;
  11. }

web server:

  • 返回增加相关cors插件
  • 一般 Access-Control-Allow-Credentialstrue 时,必须要前端 header 传递 origin 参数,值为当前前端域名 ,并且 Access-Control-Allow-Origin 不能为 *