场景

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

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

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

supported for....

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

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

 

posted on 2021-11-27 14:55  霸道流氓  阅读(897)  评论(0编辑  收藏  举报