一、在 vue.config.js 文件中进行配置
1.单域名
代码如下(示例):
module.exports = {
devServer: {
// 地址为你要实现跨域的地址
proxy: 'http://localhost:8080'
}
}
2.多域名
代码如下(示例):
module.exports = {
devServer: {
proxy: {
'/api': {
target: '<url>',
ws: true,
// changeOrigin默认是false:请求头中host仍然是浏览器发送过来的host
changeOrigin: true,
// 将代理的 /api 在请求地址中去除
pathRewrite: { "^/api": "" },
},
'/foo': {
target: '<other_url>',
ws: true,
changeOrigin: true,
pathRewrite: { "^/foo": "" },
}
}
}
}
二.在组件中使用
代码如下(示例):
import axios from "axios";
// 单域名
axios.get({
// 单域名必须是从本地出发
url:'http://localhost:8080/xxx/xxx',
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
// 多域名
axios.get({
url:'/api/xxx/xxx'
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})