Vue代理跨域详解

一、使用

项目中创建vue.config.js文件,内容如下:

module.exports = {
    devServer: {
        //跨域代理
        proxy: {
            //路径中带有/api的url,就会拦截使用代理设置;
            '/api': {
                //需要跨域的域名 (可以带路径填写)                                          
                target: 'http://www.baidu.com/api',                
                // 是否代理websocked                                    
                //ws:true,  
                // 允许跨域                                       
                changOrigin: true,
                // 重写路径                        
                pathRewrite: {  
                     // 把/api替换为空字符                                   
                     '^/api': ''                                    
                }
            }
        },
    },
}

二、原理

通过代理将接口请求url替换为跨域url

例如:

接口请求url:http://localhost:8080/api/news

红色部分为域名:http://localhost:8080

蓝色部分为路径:/api/news

let data = await axios.get('http://localhost:8080/api/news')

通过代理 判断接口请求url中含有“/api”时 拦截 使用代理配置

proxy: {
    //路径中带有/api的url,就会拦截使用代理设置;
    '/api': {
        //需要跨域的域名 (可以带路径填写)                                             
        target: 'http://www.baidu.com/api',                
        // 是否代理websocked                                    
        //ws:true,  
        // 允许跨域                                       
        changOrigin: true,
        // 重写路径                        
        pathRewrite: {  
            // 把/api替换为空字符                                   
            '^/api': ''                                    
        }
    }
},

①如果 target:'http://www.baidu.com' 不带路径(只有域名)时:

请求url中的域名 http://localhost:8080 替换为  http://www.baidu.com

请求url变为:http://www.baidu.com/api/news

请求url正确,没有多余路径

②如果 target:'http://www.baidu.com/api' 带路径时:

请求url中的域名 http://localhost:8080 替换为  http://www.baidu.com/api

请求url变为:http://www.baidu.com/api/api/news

请求url就多了一个“/api”,这时需要使用到pathRewrite: { '^/api': '';} 将路径/api/news中的/api替换为空,即http://www.baidu.com/api/news

三、注意

① 前端请求的api接口 只能是本地的,即:http://localhost:8080/api/news

② target中带域名带路径时 需要使用pathRewrite

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值