本文最后更新于:2023年12月5日 下午

前台在访问不同ip的nginx服务器时报:No ‘Access-Control-Allow-Origin’ header is present on the requested resource
原因:被请求的资源没有设置 ‘Access-Control-Allow-Origin’,也就是nginx的返回信息头没有Access-Control-Allow-Origin。

问题复现

跨域请求错误

  • 在网页前端请求访问图床文件时报错:

  • 错误信息
1
Access to fetch at 'https://uipv4.zywvvd.com:33030/HexoFiles/win11-mt/20210814144827.pdf' from origin 'https://www.zywvvd.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

问题原因

  • 被请求的资源没有设置 ‘Access-Control-Allow-Origin’,也就是nginx的返回信息头没有Access-Control-Allow-Origin

解决方案

  • 在 nginx 配置文件中的路由中添加以下代码:
1
2
3
4
5
6
7
8
9
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;
}
}
  • 如果你请求的不是"location /" ,则在自己的路由添加例如:“localhost /test”

Access-Control-Allow-Origin

  • 服务器默认是不被允许跨域的。给Nginx服务器配置Access-Control-Allow-Origin *后,表示服务器可以接受所有的请求源(Origin),即接受所有跨域的请求。

Access-Control-Allow-Headers

  • 是为了防止出现以下错误:
1
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
  • 这个错误表示当前请求Content-Type的值不被支持。其实是我们发起了"application/json"的类型请求导致的。这里涉及到一个概念:预检请求(preflight request),请看下面"预检请求"的介绍。

Access-Control-Allow-Methods

  • 是为了防止出现以下错误:
1
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

给OPTIONS 添加 204的返回

  • 是为了处理在发送POST请求时Nginx依然拒绝访问的错误

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

参考资料



文章链接:
https://www.zywvvd.com/notes/coding/internet/nginx-acc-crio-all-ori/nginx-acc-crio-all-ori/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Nginx 配置服务器解决跨域问题 has been blocked by CORS policy
https://www.zywvvd.com/notes/coding/internet/nginx-acc-crio-all-ori/nginx-acc-crio-all-ori/
作者
Yiwei Zhang
发布于
2022年5月28日
许可协议