Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to serve vue js dist/ via express js. I am using history router in vue js app.

The following are the api calls

  1. api/
  2. s-file/sending/:id
  3. terms/get/:which

As i have figured out a solution in python here. I don't know how to do it in node js with express

The code i am using right now is

app.use(function (req, res, next) {
    if (/api/.test(req.url))
        next();
    else {
        var file = "";
        if (req.url.endsWith(".js")) {
            file = path.resolve(path.join(distPath, req.url))
            res.header("Content-Type", "application/javascript; charset=utf-8");
            res.status(200);
            res.send(fs.readFileSync(file).toString());
        } else if (req.url.endsWith(".css")) {
            file = path.resolve(path.join(distPath, req.url))
            res.header("Content-Type", "text/css; charset=utf-8");
            res.status(200);
            res.send(fs.readFileSync(file).toString());

        } else {
            file = path.resolve(path.join(distPath, "index.html"))
            res.header("Content-Type", "text/html; charset=utf-8");
            res.status(200);
            res.send(fs.readFileSync(file).toString());
        }

    }
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
484 views
Welcome To Ask or Share your Answers For Others

1 Answer

Have a look at connect-history-api-fallback that is referenced in the vue docs. This should solve your problems.

Example using connect-history-api-fallback

var express = require('express');
var history = require('connect-history-api-fallback');
var app = express();

// Middleware for serving '/dist' directory
const staticFileMiddleware = express.static('dist');

// 1st call for unredirected requests 
app.use(staticFileMiddleware);

// Support history api
// this is the HTTP request path not the path on disk
app.use(history({
  index: '/index.html'
}));

// 2nd call for redirected requests
app.use(staticFileMiddleware);

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...