Nginx配置跨域请求报错Access-Control-Allow-Origin * 怎么解决

 2100

当出现403跨域错误的时候 no 'access-control-allow-origin' header is present on the requested resource,需要给nginx服务器配置响应的header参数:

一、 解决方案

只需要在nginx的配置文件中配置以下参数:

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;
 }
}

上面配置代码即可解决问题了,不想深入研究的,看到这里就可以啦=-=


二、 解释

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"的类型请求导致的。这里涉及到一个概念:预检请求(preflight request),请看下面"预检请求"的介绍。

3. access-control-allow-methods 是为了防止出现以下错误:

content-type is not allowed by access-control-allow-headers in preflight response.

4.给options 添加 204的返回,是为了处理在发送post请求时nginx依然拒绝访问的错误

发送"预检请求"时,需要用到方法 options ,所以服务器需要允许该方法。

三、 预检请求(preflight request)

其实上面的配置涉及到了一个w3c标准:cros,全称是跨域资源共享 (cross-origin resource sharing),它的提出就是为了解决跨域请求的。

跨域资源共享(cors)标准新增了一组 http 首部字段,允许服务器声明哪些源站有权限访问哪些资源。另外,规范要求,对那些可能对服务器数据产生副作用的http 请求方法(特别是 get 以外的 http 请求,或者搭配某些 mime 类型的 post 请求),浏览器必须首先使用 options 方法发起一个预检请求(preflight request),从而获知服务端是否允许该跨域请求。服务器确认允许之后,才发起实际的 http 请求。在预检请求的返回中,服务器端也可以通知客户端,是否需要携带身份凭证(包括 cookies 和 http 认证相关数据)。

其实content-type字段的类型为application/json的请求就是上面所说的搭配某些 mime 类型的 post 请求,cors规定,content-type不属于以下mime类型的,都属于预检请求:

application/x-www-form-urlencoded
multipart/form-data
text/plain

所以 application/json的请求 会在正式通信之前,增加一次"预检"请求,这次"预检"请求会带上头部信息 access-control-request-headers: content-type:

options /api/test http/1.1
origin: http://foo.example
access-control-request-method: post
access-control-request-headers: content-type
... 省略了一些

服务器回应时,返回的头部信息如果不包含access-control-allow-headers: content-type则表示不接受非默认的的content-type。即出现以下错误:

request header field content-type is not allowed by access-control-allow-headers in preflight response.


本文网址:https://www.zztuku.com/detail-14184.html
站长图库 - Nginx配置跨域请求报错Access-Control-Allow-Origin * 怎么解决
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐