9

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

    }
})
2
  • Im not clear about your requirement, is api/ is a rest api or is there any static file directories etc.. ? Commented Sep 14, 2018 at 7:49
  • all endpoints mentioned are REST Apis Commented Sep 14, 2018 at 9:15

2 Answers 2

19

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!');
});
Sign up to request clarification or add additional context in comments.

9 Comments

it will not work for vue routerlinks i.e fallbacks and moreover i am getting Cannot GET /
My bad, have a look at the use of connect-history-api-fallback in my updated answer
Error: Forbidden Your client does not have permission to get URL / from this server after deploying to docker !! what does that mean ?
@LOG_TAG this error could have many causes either in your hosting configuration or in your server code. Consider opening a separate question where you give all the background information needed: (What are you trying to do? What is working? What isn’t? What have you tried so far)
@Benno sure thanks for responding, I'm dealing with same 'Serving VueJS Builds via Express.js" using google cloud run via gcloud! wondering it's going to be duplicate one :)
|
7

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'));

2 Comments

Why is there an "async" when "await" is not being used in the function?
My man. You're the real mvp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.