如果你的前端應用和后端 API 服務器沒有運行在同一個主機上,你需要在開發環境下將 API 請求代理到 API 服務器。可以通過 *.config.js 中的 devServer.proxy 選項來配置。
config.js文件中,引入依賴項
const proxy = require('http-proxy-middleware');
devServer.proxy 可以是一個指向開發環境 API 服務器的字符串
//服務器會將任何未知請求 (沒有匹配到靜態文件的請求) 代理到http://localhost:4000上 module.exports = { devServer: { proxy: 'http://localhost:4000' } }
更多的代理控制行為:
const proxy = require('http-proxy-middleware');
module.exports = {
devServer:{
host: 'localhost',//target host
port: 8080,
//proxy:{'/api':{}},代理器中設置/api,項目中請求路徑為/api的替換為target
proxy:{
'/api':{
target: 'http://192.168.1.30:8085',//代理地址,這里設置的地址會代替axios中設置的baseURL
changeOrigin: true,// 如果接口跨域,需要進行這個參數配置
//ws: true, // proxy websockets
//pathRewrite方法重寫url
pathRewrite: {
'^/api': '/'
//pathRewrite: {'^/api': '/'} 重寫之后url為 http://192.168.1.16:8085/xxxx
//pathRewrite: {'^/api': '/api'} 重寫之后url為 http://192.168.1.16:8085/api/xxxx
}
}}
},
//...
}
