前端解决跨域问题

第一种方案 node 代理


1、安装node (^10.0版本以上)
2、使用NodeJs反向代理http请求
3、nodejs项目路径下初始化
npm init 然后 一路回车
4、使用npm包管理器安装express和http中间件代理模块
npm install express http-proxy-middleware --save-dev
5、新建 server.js
里面写入

中间件 http-proxy-middleware 原理和用法(https://www.cnblogs.com/zhaoweikai/p/9969282.html)
6、启动node 服务
node server.js
访问 http://ip:port/index.html
7、查看静态资源 跨域的问题

第二种方案

思路
Nginx 具体配置如下:
server {
listen 83;
server_name iot.inteliot.net;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    # gzip config
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 9;
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";


   location ^~ /sea/ {
        # 用于配合 browserHistory 使用
        proxy_pass http://ip:82/;
        proxy_set_header   X-Real-IP         $remote_addr;
        proxy_set_header   Host              $http_host;
        proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
        # 如果有资源,建议使用 https + http2,配合按需加载可以获得更好的体验
        # rewrite ^/(.*)$ https://myzuul.com:9527/$1 permanent;
    }

    location ^~ /ui/ {
        add_header 'Access-Control-Allow-Origin' *;
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
        proxy_pass http://ip:5601/;
        proxy_set_header   X-Real-IP         $remote_addr;
        proxy_set_header   Host              $http_host;
        proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
    }
}

在我们阿里云(已开放83端口)上测试的
接口换成 83 http://ip:83/ui/internal/search/es
页面也可以换成 83 http://ip:83/sea/searchui.html

posted @ 2021-04-09 14:57  王吉平  阅读(110)  评论(0编辑  收藏  举报