vue配置代理服务器精讲
如果你的前端应用和后端 API 服务器没有运行在同一个主机上(跨域),你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。
devServer.proxy 可以是一个指向开发环境 API 服务器的字符串:
module.exports = {
devServer: {
proxy: http://localhost:5000
}
}
这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理 http://localhost:5000。
用于测试的node服务器(请求之后返回一些人员信息,端口号为5000)
//引入 express
const express = require(express)
//实例化 express
const app = express()
//解析json字符串
app.use(express.json())
app.use(express.urlencoded({ extended:false }))
app.get(/test,(req,res)=>{
res.send([
{name:小明,age:18},
{name:小花,age:20}
])
})
app.listen(5000,()=>{
console.log(服务器已启动:http://127.0.0.1:5000);
})
向服务器发送请求
axios.get(/test).then(
response=>{
console.log(response.data)
},
)
当然路径也可写为
流程
1.当静态文件夹public找不到test时,就走代理,实际请求地址为 http://localhost:5000/test
浏览器输出内容为:
2.当静态文件夹public能找到test时,不走代理,如下:
浏览器输出内容为index.html的内容
方法二
带前缀的
axios.get(http://localhost:8080/api1/test).then(
response=>{
console.log(response.data)
},
)
devServer: {
proxy: {
/api1: { // 匹配所有以 /api1开头的请求路径
target: http://localhost:5000,// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {^/api1: } //将/api1替换成空字串,实际请求地址不会带上该路径
},
/api2: { // 匹配所有以 /api2开头的请求路径
target: http://localhost:5001,// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {^/api2: }
}
}
}
// changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
// changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
浏览器依然正常输出
记得请求的地址写本机就行,千万不要写实际的请求的地址,配置了代理后,会自动给你代理到你所请求的服务器地址,且修改了vue.config.js文件后需重启项目 。
