配置vue.config.js处理前端跨域问题
这个地址在浏览器是可以直接打开访问
例子 完整路径 https://www.vue-js.com/api/v1/topics
在vue项目中使用
代码如下:
//点击按钮触发使用axios去掉接口
handleNew() {
console.log('点击了跨域');
axios({
url: 'https://www.vue-js.com/api/v1/topics',
method: 'get',
}).then(res => {
console.log('res',res)
});
},
结果报错如图:(发生了跨域)
解决:
// 在vue项目中找到vue.config.js文件 进行配置
// 完整路径 https://www.vue-js.com/api/v1/topics
// 以下我分了两种写法 '/api'的和 'topics'
devServer: {
proxy: {
//方法一
'/api': {//代理标识,一般是每个接口前的相同部分 就是在域名后面拼接的参数
target: 'https://www.vue-js.com', // 这跨域的域名和端口号 不需要写路径
changeOrigin: true, // 允许跨域请求
},
//方法二
'/topics': { //代理标识可以随便写 topics topics1 top... 都行
target: 'https://www.vue-js.com', // 这跨域的域名和端口号 不需要写路径
changeOrigin: true, // 允许跨域请求
pathRewrite:{ //用来做替换配置的
'^/topics':'/api/v1/topics' //可以替换成空或者其他路径
}
}
},
},
使用方法一点击跨域按钮
//使用axios访问'/api/v1/topics'路径识别'/api'标识并不替换所以就会用传进来的地址('/api/v1/topics')然后会代理成 target + '/api/v1/topics' ==> https://www.vue-js.com/api/v1/topics
handleNew() {
console.log('点击了跨域');
axios({
url: '/api/v1/topics',
method: 'get',
}).then(res => {
console.log('res',res)
});
},
使用方法二点击跨域按钮
//使用axios访问'/topics'路径识别'/topics'标识先替换成'/api/v1/topics' 然后会代理成 target + pathRewrite ==> https://www.vue-js.com/api/v1/topics
handleNew() {
console.log('点击了跨域');
axios({
url: '/topics',
method: 'get',
}).then(res => {
console.log('res',res)
});
},
因为是修改了vue.congig.js文件,最后重新运行一下项目 重新点击跨域按钮可以访问