3

I have configured nginx to pass all requests to Node:

server {
    listen 80;
    server_name domain.tld;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

On the server I have a Node app running Express which servers my Vue index file.

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/app/index.html`);
});

I want to use HTML5 history mode with Vue router, so I set mode: 'history' in the router settings. I installed connect-history-api-fallback and set it up:

const history = require('connect-history-api-fallback');
app.use(history());

The routes works fine if the user first hits http://domain.tld. But, if a subroute is accessed directly, or the page is refreshed, I get a not found error.

How do I change my configuration?

1
  • Is it wise to use a node app to serve the file? Wouldn't it be better to use e.g. nginx in terms of resources? Commented Oct 17, 2017 at 14:35

2 Answers 2

3

I had the same problem.

It won't work when the order is:

app.use(express.static('web'));
app.use(history());

,but will work when:

app.use(history());
app.use(express.static('web'));

Whole example app:

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

app.use(history());
app.use(express.static('web'));

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

In web folder i have:
index.html
and other js, css files.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't understand how your answer has not picket as the correct one. This fixed it for me and I can now use the package
Yes this! This fixed it for me, artuu can you explain why swapping history/static fixes it?
2

As I couldn't get the connect-history-api-fallback library working, I created one myself:

app.use((req, res, next) => {
  if (!req.originalUrl.includes('/dist/', 0)) {
    res.sendFile(`${__dirname}/app/index.html`);
  } else {
    next();
  }
});

This will send the /app/index.html when requested anything but /dist where scripts and images are located.

Comments

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.