故障现象
在使用 XMLHttpRequest 向另外一个站点发起跨域请求时,由于浏览器出于安全考虑实施了同源策略,阻止了页面的资源交互请求,导致 Console 控制台出现了如下报错:
Access to XMLHttpRequest at ‘http://test.kobin.cn/api/public/wordpress/’ from origin ‘http://www.kobin.org’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
要解决这个问题,我们需要在服务端配置 CORS 头部,告诉浏览器哪些跨域请求是安全的,从而解决跨域请求问题。在本篇文章的测试环境中,服务端使用了宝塔面板 8.0.6 版本,Nginx 服务为 1.24.0 版本。
操作步骤
1、登录宝塔面板,选择「网站」,进入到对应的站点设置。

2、在列表中选择「配置文件」。

3、例如请求来源是 www.kobin.org ,则将以下代码添加到 Nginx 配置文件当中。这些选项可能不适用于所有情况,具体需要取决于您的应用程序和环境进行修改调整。
set $dom 'no';
if ($http_origin ~* (https?://www\.kobin\.org(:[0-9]+)?$)) {
set $dom $http_origin;
}
add_header 'Access-Control-Allow-Origin' $dom;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Range';
if ($request_method = 'OPTIONS') {
return 204;
}

4、如果服务端允许任何来源的跨域请求,可以使用以下配置。但是在某些情况下可能存在安全风险,建议根据实际需求设置允许的具体来源,而不是使用通配符。
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' 'Origin, Content-Type, Accept, DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Range';
if ($request_method = 'OPTIONS') {
return 204;
}
5、保存完成后建议重载 Nginx 配置。

本文为原创文章,著作权归作者所有:来自「KOBIN 技术随笔」作者的原创作品,转载请标明出处。
宝塔面板处理 CORS 跨域请求问题
https://blog.kobin.cn/blog/system/s2/3062.html
宝塔面板处理 CORS 跨域请求问题
https://blog.kobin.cn/blog/system/s2/3062.html
评论列表(1条)
感谢分享,谢谢