Reputation: 167
I have vue app that is running at http://localhost:8080/
(through Vue CLI) and backend running on Express at http://localhost:7070
. Is it possible to run frontend and backend under the same address (while not losing hot module replacement from Vue CLI server)?
Upvotes: 5
Views: 8205
Reputation: 1
Since Vue is only a frontend library, the easiest way to host it and do things like serve up assets is to create a simple Express friendly script that you can use to start a mini-web server. Read up quickly on Express if you haven’t already. After that, add express:
npm install express --save
Now add a server.js
file to your project’s root directory :
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 7070;
var hostname = '127.0.0.1';
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
after that you could run :
node server
and your project will be served at the given host and port
Assuming that you have already the dist
directory, if you don't have it run :
npm run build
in order to generate it and you don't need to run npm run serve
or npm run dev
for ruuning Vue app
Upvotes: 3
Reputation: 496
What you're looking for is the devServer option. If you're using vue cli 3, create a vue.config.js file in your main app directory, then add this block:
module.exports = {
configureWebpack:{
},
devServer:{
host: 'localhost',
hot:true,
port: 8080,
open: 'Chrome',
proxy: { //https://cli.vuejs.org/guide/html-and-static-assets.html#disable-index-generation
'/*':{ //everything from root
target: 'http://localhost:3000',
secure: false,
ws: false,
},
'/ws/': { //web sockets
target: 'http://localhost:3000',
secure: false,
ws: true
},
'!/':{ //except root, which is served by webpack's devserver, to faciliate instant updates
target: 'http://localhost:3000/',
secure: false,
ws: false
},
}
}
}
The port for your frontend can be on 8080 or whatever, and your backend on 7070, and you proxy your requests from your frontend node server on 8080 to your backend node server on 7070. This is for vue cli 3. For earlier versions you have to put the devServer option somewhere else IIRC, but I forget where. If you have problems with this, ask me and I can check it out.
Upvotes: 5