我正在使用vue-cli
webpack-simple
模板来生成我的项目,我想要代理请求到一个独立的后端服务器。如何轻松实现这一点?
我正在使用vue-cli
webpack-simple
模板来生成我的项目,我想要代理请求到一个独立的后端服务器。如何轻松实现这一点?
vue.config.js
文件放在项目的根目录下。// vue.config.js
module.exports = {
devServer: {
proxy: {
"/gists": {
target: "https://api.github.com",
secure: false
}
}
}
};
现在,任何对http://localhost:8080/gists
的调用(假设您的开发服务器位于localhost:8080
)将被重定向到https://api.github.com/gists
。
假设您有一个本地后端服务器通常部署在localhost:5000
上,并且您想将所有对/api/anything
的调用重定向到该服务器。使用:
// vue.config.js
module.exports = {
devServer: {
proxy: {
"/api/*": {
target: "http://localhost:5000",
secure: false
}
}
}
};
devServer
Webpack 文档:https://webpack.js.org/configuration/dev-server/#devserverproxy - Doug Wilhelm如果您使用vue-cli
的webpack
模板,则可以在此参考文档中找到所需信息:
http://vuejs-templates.github.io/webpack/proxy.html
或者,您可以将webpack
模板中相关配置复制到本地的webpack-simple
模板中,而无需现在更改模板。
编辑:来自我的本地设置的更多信息
这是我在config/index.js
中在module.exports
下所拥有的内容:
dev: {
env: require('./dev.env'),
port: 4200,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
},
'/images': {
target: 'http://localhost:8080',
changeOrigin: true
},
// and so on...
上述配置将我的vue-cli
运行在端口4200上,而我将我的服务器运行在端口8080上。dev.proxyTable
中的changeOrigin
选项(在webpack配置中)确保您不需要在服务器API响应上提供CORS标头。changeOrigin
,则需要确保您的服务器API在其响应标头中包含Access-Control-Allow-Origin: *
(或等效内容)。changeOrigin: true
。代理服务器是使用http-proxy-middleware完成的 - 这个github页面证实了changeOrigin
选项将主机头更改为服务器URL(目标)。 - Manimodule.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://genius.net',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
},
'/auth': {
target: 'http://genius23.net',
changeOrigin: true,
pathRewrite: {
'^/auth': ''
}
},
}
}
};
vue-cli
的样板文件,而是使用了yeoman的这个生成器。即使我对webpack/gulp/browser-sync知之甚少(尽管在我试图将其与后端集成时有一些小问题),它也让我入门了。我认为值得一看,并在vue-cli
和它之间做出选择。 - JJPandari