Nginx映射本地静态资源时,浏览器提示跨域问题解决

时间:2022-09-17 00:51:24


场景

本地html中请求磁盘中的静态资源文件,可以使用Nginx做静态资源映射,

可以将本地磁盘文件映射为网络url。可是由于浏览器的跨域机制会提示:

from orihin 'null' has been blocked by CROS policy: Cross origin requersts are only

supported for....

Nginx映射本地静态资源时,浏览器提示跨域问题解决

 

注:

博客:​​BADAO_LIUMANG_QIZHI的博客_霸道流氓气质-C#,SpringBoot,架构之路领域博主​​

关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

1、编辑nginx.conf,添加如下代码

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、完整server代码

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

listen 120;
server_name 127.0.0.1;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root D:/WorkSpace/Gitee/three-js-study/assets/;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}