vue-cli配置代理服务器(devServer.proxy)
方式一
这种方式只能配置一个,并且不能自由的决定请求是否经过代理服务器
module.exports = {
devServer: {
proxy: 'http://localhost:4000'
//这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000
}
}
方式二(可配置多个)
module.exports = {
devServer: {
proxy: {
'/api': { // 若请求的前缀不是这个'/api',那请求就不会走代理服务器
target: '<url>', //这里写路径 如: http://localhost:5000
pathRewrite:{'^/api':''} //将所有含/api路径的,去掉/api转发给服务器
ws: true, //用于支持websocket
changeOrigin: true //用于控制请求头中的host值
},
'/demo': {
target: '<url>' //这里写路径,和上面一样
}
}
}
}
使用时如下:
axios.get('http:localhost:8080/api/student').then(
response =>{
console.log('请求成功',response.data)
},
error =>{
console.log('请求失败',error.message)
}
)