方法一
在vue.config.js添加如下配置:
devServer: {
proxy: "http://localhost:5000"
}
说明:
1、优点:配置简单,请求资源时直接发给前端(8080)即可
2、缺点:不能配置多个代理,不能灵活的控制请求是否走代理
3、工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么请求会转发给服务器(优先匹配前端资源)
方法二:
在vue.config.js添加如下配置:
module.exports = {
devServer: {
proxy: {
'/api': { // 匹配所有以'/api'请求开头的路径
target: 'http://localhost:5000',// 代理目标的基础路径
ws: true, // websocket协议
changeOrigin: true,
pathRewrite: {'^/api': ''} // 正则将'/api'替换为空字符串
},
'/foo': {
target: '<other_url>'
}
}
}
/*
changeOrigin设置为true时,服务器收到的请求头中的host为: localhost:5000
changeOrigin设置为false时,服务器收到的请求头中的host为: localhost:8080
changeOrigin默认值为true
*/
}
在组件中使用:
getPublishList() {
// axios 定义上传方法
axios({
method: 'get',
url: `/sell/getSellPublisherList`, // 或者 url: `http://localhost:8080/sell/getSellPublisherList`
headers: {
'Content-Type': 'application/json;charset=UTF-8'
} // 请求头
}).then(
res => {
if (res.status === 200) {
const pubArr = res.data
}
},
err => console.log(err)
).catch(
err => console.log(err)
)
},