简体   繁体   中英

How can I serve my Vuejs front end files from my node/express server?

基本上,我有两条路线,其中一条用于主页,另一条用于管理页面,但是我找不到关于如何组合Vuejs和Express的好的文档,因此我可以在两个页面同时服务的前提下假设两个UI都不同。组件的构造不同。

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM