Serving VueJS Builds via Express.js using history mode

你。 提交于 2020-07-26 07:54:07

问题


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());
        }

    }
})

回答1:


Original answer

You can use express.static() to serve all files within a directory. Your API routes should be handled separately.

Example:

var express = require('express');
var app = express();

// Serve all the files in '/dist' directory
app.use(express.static('dist'));

// Handle a get request to an api route
app.get('/your-api-route/:id', function (req, res) {

  // You can retrieve the :id parameter via 'req.params.id'
  res.send(`Did GET /your-api-route/${req.params.id}!`);
});

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

Update 1: Added example

Update 2: Altered example to what should be the correct usage (https://github.com/bripkens/connect-history-api-fallback/tree/master/examples/static-files-and-index-rewrite)

I missed the history part, my bad. Have a look at connect-history-api-fallback that is referenced in the vue docs. This should solve your problems?

Updated 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 
app.use(history({
  index: '/dist/index.html'
}));

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

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



回答2:


The very simpler one if anyone wants to use

Just add this below all the valid routes and above app.listen

app.all("*", (_req, res) => {
  try {
    res.sendFile('/absolute/path/to/index.html');
  } catch (error) {
    res.json({ success: false, message: "Something went wrong" });
  }
});

Make sure you have included

app.use(express.static('/path/to/dist/directory'));


来源:https://stackoverflow.com/questions/52327143/serving-vuejs-builds-via-express-js-using-history-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!