vue cli 解决跨域 线上 nginx 反向代理配置

前后分离 axios 接 api 跨域问题如图:

解决办法:

1. npm start 本地开发环境解决:

在webpack配置文件 /config/index.js 里找到 proxyTable 开启代理 changeOrigin:true,

复制代码
proxyTable: {
      '/api':{
        target:'http://xx.xx.xx.xx:5568',
        changeOrigin:true,
        pathRewrite:{
            '^/api':'/api'
        }
      }
    },
复制代码

2. npm run build 把 dist 放线上后解决:

nginx 的 配置文件 xx.conf 的 server {} 里加如下:

复制代码
location /api/ {
        # 把 /api 路径下的请求转发给真正的后端服务器
        proxy_pass http://xx.xx.xx.xx:5568;

        # 把host头传过去,后端服务程序将收到your.domain.name, 否则收到的是localhost:8080
        proxy_set_header Host $http_host;

        # 把cookie中的path部分从/api替换成/service
        proxy_cookie_path /api /;

        # 把cookie的path部分从localhost:8080替换成your.domain.name
        proxy_cookie_domain localhost:80 http://xx.xx.xx.xx:5568;
    }
复制代码

重新启动一下 nginx 

/etc/init.d/nginx reload

 api 跨域 访问成功

猜你喜欢

转载自www.cnblogs.com/yaowen/p/10559586.html