Proxy requests to a separate backend server with vue-cli
In @vue/cli 3.x:
- Create a
vue.config.js
file in the root folder of your project, if you don't already have one. - Have its contents as follows:
// vue.config.js
module.exports = {
devServer: {
proxy: {
"/gists": {
target: "https://api.github.com",
secure: false
}
}
}
};
Now any call to (assuming your dev server is at localhost:8080
) http://localhost:8080/gists
will be redirected to https://api.github.com/gists
.
Another example: proxying all calls
Say you have a local backend server that is typically deployed at localhost:5000
and you want to redirect all calls to /api/anything
to it. Use:
// vue.config.js
module.exports = {
devServer: {
proxy: {
"/api/*": {
target: "http://localhost:5000",
secure: false
}
}
}
};
If you use webpack
template with vue-cli
, then you can find the required information in this reference document:
http://vuejs-templates.github.io/webpack/proxy.html
Or instead of changing your template now, you may copy the relevant config from the webpack
template into your local webpack-simple
template.
EDIT: more info from my local setup
This is what I have in my config/index.js
under 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...
The above config runs my vue-cli
on port 4200, and I run my server on port 8080.
EDIT: Corrected info about CORS after comment #4 and #5
Note:
- The
changeOrigin
option indev.proxyTable
(in webpack config) ensures that you do not need to serve CORS headers on your server API responses. - If you decide to omit
changeOrigin
for any reason, then you need to ensure that your server API includesAccess-Control-Allow-Origin: *
(or equivalent) in its response headers.
References:
- https://stackoverflow.com/a/36662307/654825
- https://github.com/chimurai/http-proxy-middleware
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://genius.net',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
},
'/auth': {
target: 'http://genius23.net',
changeOrigin: true,
pathRewrite: {
'^/auth': ''
}
},
}
}
};