vue-cli3配置跨域代理

6 篇文章 0 订阅
4 篇文章 0 订阅

在vue.config.js中添加devServer.proxy配置

单个接口地址代理配置
module.exports = {
    devServer: {
    	// 配置代理
        proxy: {
            //代理接口前缀为/api的请求
            '/api': { 
                target: 'https://www.lihefei.com', //需要代理到的目标地址
                ws: true,
                changOrigin: true, //是否跨域
                pathRewrite: {
                    '^/api': '' //重写路径
                }
            }
        }
    }
};
多个接口地址代理配置
module.exports = {
    devServer: {
        proxy: {
            '/api': { 
                target: 'https://www.lihefei.com', 
                ws: true,
                changOrigin: true, 
                pathRewrite: {
                    '^/api': '' 
                }
            },
            '/abc': {
                target: 'https://www.zhangsan.com',
                ws: true,
                changOrigin: true, 
                pathRewrite: {
                    '^/abc': '' 
                }
            },
            '/xyz': {
                target: 'https://www.lisi.com',
                ws: true,
                changOrigin: true, 
                pathRewrite: {
                    '^/xyz': '' 
                }
            }
        }
    }
};
实际应用

假设项目启动后的访问地址是:http://localhost:8080,需要代理访问地址是:https://www.lihefei.com

axios.defaults.baseURL = ''; //baseURL为空时,会默认使用项目地址http://localhost:8080

axios.get('/api/user')
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  })
  .then(() => {
    // always executed
  });

浏览器的请求头里的Request URL是:http://localhost:8080/api/user
而代理后实际请求的Request URL是: https://www.lihefei.com/user

参考链接:
Vue CLI 3 本地代理和跨域

Webpack-dev-server的proxy用法

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值