vue, node和nginx配合做前端开发,并且调用后台服务,解决CORS(Access-Control-Allow-Origin)错

1 篇文章 0 订阅

Vue整合nginx:(1)开发环境npm run dev下,通过nginx解决前后端分离造成的跨域问题:CORS(Access-Control-Allow-Origin)错
假设vue的dev server端口是8380, 后台REST服务端口是8081, nginx的配置如下:

    server {
        listen       80;
        server_name  dev.abc.cn;
        index index_en.html index.html;
        proxy_cookie_domain dev.abc.cn fintechp.cn;
        proxy_cookie_domain localhost fintechp.cn;

        location / {
          proxy_pass http://localhost:8380;
          proxy_redirect off;
          proxy_set_header   Host             $host;
          proxy_set_header   X-Real-IP        $remote_addr;
          proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        }
        location /ifp-web-yz/ { #转发到 http://localhost:8081/ifp-web-yz/xxx
          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 'Set-Cookie,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
          proxy_pass http://localhost:8081;
          proxy_redirect default;
        }
        location ^~ /risk-views/ { #转发到 http://localhost:8088/xxx
          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 'Set-Cookie,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
          proxy_pass http://localhost:8088/;
          proxy_redirect default;
        }
    
    }

注意,浏览器访问地址:http://dev.abc.cn/
hosts文件中,添加 127.0.0.1 dev.abc.cn

也可以不用nginx,直接使用vue server做反射代理:
vue.config.js

module.exports = {
  devServer: {
    proxy: {
      '/risk-views': {
        target: 'http://localhost:8088', #springboot服务
        // ws: true,
        changeOrigin: true,
		pathRewrite:{
			'^/risk-views':'/' #代理转发时,去掉/risk-views
		}

      }
    //   如果后端接口不止一个 就可以继续如下代码配置
    // '/foo': {
    //   target: '<other_url>'
    // }
    }
  }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值