跨域问题总结系列(一)

一、mac本地打开不含跨域的浏览器便于开发方案

1、在文稿中新建一个文件夹存储无跨域的chrome的用户数据;

cd /Users/hahahademac/Documents; // 进入文稿(也可以是其他文件)
mkdir chromeConfig; // 创建存储新浏览器数据的文件夹

2、执行如下指令

ps:重新打开一个新的chrome浏览器,不带有跨域限制。
open -n /Applications/Google\ Chrome.app/ --args --disable-web-security  --user-data-dir=/Users/LeoLee/Documents/chromeConfig
ps:重新打开一个新的chrome浏览器,包含跨域限制,只需将上面的disable 换成 enable 即可,如下。
open -n /Applications/Google\ Chrome.app/ --args --enable-web-security  --user-data-dir=/Users/LeoLee/Documents/chromeConfig

3、执行完毕,打开的新的chrome浏览器,此浏览器无视跨域原则,会出现下图所示:

在这里插入图片描述

二、CORS(跨站资源共享):目前解决跨域问题主流方案

第一种方式:nginx配置开启CORS

1、vim进入服务器配置文件
vim /etc/nginx/config.d
2、开启nginx允许跨域方案;
ps:下方的 add_header 部分就是配置项。
server {

        # listen 8880;
        # listen 80;
        listen 443 ssl http2;
        server_name tpdoc.cn;
        root /data/topay/tpdoc_api_new;
        index index.html index.php;
        access_log   /var/log/nginx/access_erp.log;
        error_log   /var/log/nginx/error_erp.log;
        client_max_body_size 8M;
        client_body_buffer_size 128k;

        # set expiration of assets to MAX for caching
        location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
                expires max;
                log_not_found off;
        }

        location ~* \.php$ {
                fastcgi_pass 127.0.0.1:9000;
                proxy_read_timeout 1200;
                proxy_connect_timeout 1200;
                include fastcgi.conf;
        }

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

            # Check if a file or directory index file exists, else route it to index.php.
            try_files $uri $uri/ /index.php;
        }


}

第二种方式:后端代码中加入跨域配置

ps:一般统一一个模块,每个模块引入这个跨域配置,不同语言各不相同;其实就是请求头和相应头进行控制。

发布了7 篇原创文章 · 获赞 3 · 访问量 552

猜你喜欢

转载自blog.csdn.net/weixin_44953136/article/details/105479028