官方文檔中指明,跨域請求可以通過配置vue.config.js
中的devServer.proxy
選項來進行配置。
這個選項配置的本質實際上就是http-proxy-middleware
中間件的用法,和Webpack-dev-server
的proxy一樣。
vue-cli 3.0中介紹了兩種常見的用法:
module.exports = {devServer: {proxy: 'http://localhost:4000'}
}
這種用法是將任何未知請求 (沒有匹配到靜態文件的請求) 代理到http://localhost:4000
如果想單獨配置,可以使用path: options
成對的對象進行配置
module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:4000',ws: true,changeOrigin: true},'/foo': {target: 'http://localhost:8000'}}}
}
上述配置指明:
將請求到/api/xxx
代理到http://localhost:4000/api/xxx
,
將請求到/foo/xxx
代理到http://localhost:8000/foo/xxx
其他詳細配置可以百度http-proxy-middleware
配置