vue 跨域proxy路径的正确配法

一直以来没弄懂使用vue3.0proxyvue2.0 proxyTable路径的正确配法。每次以为配对了结果一直出错,只有多尝试几次后才正确,直到某一天,终于理解了这到底是什么原理。

不废话,直接上代码,我们要请求的路径为:

http://localhost:3000/api/todos

vue3.0为例,在项目根目录下新建vue.config.js文件,添加以下代码:

module.exports = {
    devServer: {
        proxy: {
            '/api': //代理标识
                {
                target: 'http://localhost:3000/api', //代理路径
                changeOrigin: true,
                pathRewrite: {
                  // 标识替换
                  // 原请求地址为 /api/todos 将'/api'替换''时,
                  // 代理后的请求地址为: http://localhost:3000/api/todos
                  // 若替换为'/other',则代理后的请求地址http://localhost:3000/api/other/todos 
                    '^/api': ''
                }
            }
        }
    }
}

使用axios请求的代码为:

let url = '/api/todos';
this.$axios.get(url)
.then(response=>{
    console.log(response)
 })
.catch(error=>{
    console.log((error));
});     

整个过程可以概括为以下几步:

1. proxy检查我们的请求的url : /api/todos有没有代理标识/api,如果有的话,在url前加上代理路径,即整个url

http://localhost:3000/api/api/todos

2. pathRewrite中的^/api会把代理标识/api替换为空,即整个url变为:

http://localhost:3000/api/todos

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值