Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving VueJS Builds via Express.js using history mode

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

    }
})
like image 354
tbhaxor Avatar asked Sep 14 '18 07:09

tbhaxor


People also ask

What is history mode in Vue?

The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. To get rid of the hash, we can use the router's history mode, which leverages the history.


2 Answers

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!');
});
like image 79
Benno Avatar answered Oct 24 '22 05:10

Benno


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'));
like image 22
tbhaxor Avatar answered Oct 24 '22 04:10

tbhaxor