
How to setup Vue dev server with a running Web Server
When you need to communicate with a real world back-end
Problem
Imagine you have your back-end server running on your computer and you want to use “npm run dev” as usual to have a better development experience but you need to make API calls to your back-end.
So how to do that? You need to proxy.
Solution
I assume you created your Vue project with the standard command-line interface, vue init webpack. If so, your directory structure should be something like:
.
├── build
├── config
├── index.html
├── node_modules
├── package.json
└── srcIn this example we also assume that you API server is living at localhost:8080 and the Vue dev server is at localhost:3000. We need a way to proxy all the request from the dev server to the real one.
Open config/index.js and you should see a big JSON:
module.exports = {
build: {
//magic stuff
},
dev: {
env: require('./dev.env'),
port: 3000,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
cssSourceMap: false
}
}In the dev field you can notice a proxyTable object. This is where we need to add our proxy configuration. In our case we want to proxy all the request with the /api to localhost:8080.
Therefore:
proxyTable: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
},We can add also multiple configuration. For example, Imagine we need to fetch the images from another server running at localhost:8081.
proxyTable: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
},
'/images': {
target: 'http://localhost:8081',
changeOrigin: true
}
},Since Vue uses webpack to create the dev server, you can check here for more information:
https://webpack.github.io/docs/webpack-dev-server.html
Run npm run dev and everything should work!
Conclusion
Using the Vue dev server with a real running back-end is really easy and require a minimum setup. I hope you find this quick tutorial useful.
Thank you for reading.
Francesco Saverio

