vue开发模式 跨域处理

大家在做vue开发的时候难免会遇到跨域的问题,一般解决的办法有两种,后端配置cors,大部分框架都集成了相应的配置文件,另一种就是前段设置反向代理,而笔者今天要说的就是vue生产模式的反向代理。

  vue cli 2.x:

   

proxyTable: {
      // proxy all requests starting with /api to jsonplaceholder
      '/api': {
        target: 'http://localhost:1337',      //目标服务器,注意要到端口号
        changeOrigin: true,						//是否跨域
        pathRewrite: {
          '^/api': ''                                      //重写api使得 /api/login -> http://localhost:1337/login等等,这里好多csdn博主跟我的不一样,可能个人喜好问题,只要映射到相应的url就行了
        }
      }
    },

  

  vue cli 3.x:

先安装一个插件

  

yarn add @cnamts/vue-cli-plugin-proxy # OR npm install @cnamts/vue-cli-plugin-proxy

  

//vue.config.js 注意是在根目录下
module.exports = {
    pluginOptions: {
        proxy: {
            enabled: true,
            context: '/api',
            options: {
                target: 'http://192.168.43.106:8080',
                changeOrigin: true,
                ws:true,                                            //websocket
                pathRewrite:{
                    '^/api':''
                }
            }
        }
    }
}

  

下面有个例子

本文链接:https://blog.csdn.net/my_csdn2018/article/details/82909989

对反向代理解决跨域过程的理解

如图,浏览器中请求的url为http://localhost:8081/api/portal/order/queryOrderRow?orderNumber=4015
我实际请求的url为http://localhost:8080/portal/order/queryOrderRow?orderNumber=4015
本地项目通过http://localhost:8081/#/在浏览器中进行访问。

通过伪造请求使得http请求为同源的,然后将同源的请求发送到反向代理服务器上,由反向代理服务器去请求真正的url,这样就绕过直接请求真正的url导致跨域问题。

猜你喜欢

转载自www.cnblogs.com/liliuyu/p/11700302.html