2
votes

Basically I have two routes with express one for the home page and other for the admin page, but I cannot find a good documentation on how to combine Vuejs and Express so I can serve at the same time both pages assuming that both have differents UI's so the components are not constructed the same.

2
Are they 2 separate vue-cli projects? What do the routes look like? Are you using vue-router in history mode?towc
I am not using the vue-router (not yet, since I my app doesn't have multiple pages/components to render) and probably I would have to make 2 separate vue-cli projects only if I finally use the vue-cli webpack templates.Ahsath

2 Answers

1
votes

To use vue-router and avoid running into 404 issues, your express.js has to have a fallback that serves the index.html. Here is a vue guide on how to do it https://router.vuejs.org/en/essentials/history-mode.html

0
votes

To serve static files with expressjs you need to use the static middleware.

It accepts the directory name as the first argument. This directory shall contain all the static files to be served.

const express = require('express');
let app = express();
app.use(express.static('public')); // NAME OF THE DIRECTORY IS PUBLIC

const serverPort = 3000;

const respHttpOptions = {
    root: `public/`,
    dotfiles: 'deny',
    headers: {
        'dina-timestamp': Date.now(),
        'my-xxx-header': true
    }
};
app.get('/', (req, resp) => { // HANDLE THE REQUEST HERE
    resp.sendFile('index.html', respHttpOptions, (err) => {
        // SEND INDEX.HTML INSIDE PUBLIC DIRECTORY
        if (!err)
            console.log(sucL(`Served index.html`));
        else
            console.log(errL(`Failed to serve index.html ${err}`));
    })
});

try {
    app.listen(serverPort);
    console.log(sucL(`Server started at ${serverPort}`));
} catch (e) {
    console.log(errL(e));
}

There is no distinction for vuejs! You could have multiple directories inside the static directory.