一、使用
项目中创建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