nginx解决跨域问题

当出现403跨域错误的时候 No 'Access-Control-Allow-Origin' header is present on the requested resource,须要给Nginx服务器配置响应的header参数:
1、 解决方案
只须要在Nginx的配置文件中配置如下参数:json

location / {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    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';
    if ($request_method = 'OPTIONS') {
        return 204;
    }
}

上面配置代码便可解决问题了,不想深刻研究的,看到这里就能够啦=-=
2、 解释segmentfault

  1. Access-Control-Allow-Origin
    服务器默认是不被容许跨域的。给Nginx服务器配置Access-Control-Allow-Origin *后,表示服务器能够接受全部的请求源(Origin),即接受全部跨域的请求。
  2. Access-Control-Allow-Headers 是为了防止出现如下错误:
    Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
    这个错误表示当前请求Content-Type的值不被支持。实际上是咱们发起了"application/json"的类型请求致使的。
  3. Access-Control-Allow-Methods 是为了防止出现如下错误:
    Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.跨域

  4. 给OPTIONS 添加 204的返回,是为了处理在发送POST请求时Nginx依然拒绝访问的错误
    发送"预检请求"时,须要用到方法 OPTIONS ,因此服务器须要容许该方法。

PHP解决跨域问题,加入header头:服务器

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header('Access-Control-Allow-Headers:x-requested-with,content-type');

原文地址:
http://www.javashuo.com/article/p-zlhfinyg-gq.html
https://blog.csdn.net/HQB421/article/details/80505073app

相关文章
相关标签/搜索