0

In this code

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

app.use(history({
    index: 'Trading Inquiry/index.html'
}));
app.use(express.static(path.join(__dirname, 'Trading Inquiry')));
app.get('/', function (req, res) {
    console.log(1);
    res.sendFile('Trading Inquiry/index.html');
});

var server = app.listen(process.env.PORT || 3000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('My site started at http://%s:%s', host, port);
});

I set it up so that links are relative to the folder Trading Inquiry. Plus ig the / route is given, return the index.html file, and for routes that don't match, then also return the index.html file. However when I visit http://localhost:3000, I get

Cannot GET /

This works though

http://localhost:3000/index.html

Does anyone know what's wrong?

Thanks

1
  • Works on my computer when I comment out app.use(history({index: 'Trading Edit: Also works if I use app.use(history()) without any index parameter Commented Oct 30, 2018 at 2:24

1 Answer 1

1

res.sendFile doesn't use express public path, so you have to mention the absolute path of file while sending it.

res.sendFile(path.join(__dirname, 'Trading Inquiry', 'index.html'));

Another solution(the one I prefer),

If you provide '/' as first argument for express static middleware, the the file name index.html will be rendered.

So if you change below line:

app.use('/', express.static(path.join(__dirname, 'Trading Inquiry')));

You will not need a get route for index.html, so below code is not required.

app.get('/', function (req, res) {
    console.log(1);
    res.sendFile('Trading Inquiry/index.html');
});
Sign up to request clarification or add additional context in comments.

3 Comments

But if I do this, any other files in the root folder will be accessible?
@omega, Yeah other routes will also work. And I don't understand why are you using 'connect-history-api-fallback' , it's usually used for a Single page Application having single index.html , so if you remove " app.use(history(...)) ", all the routes will work fine
It needs a general fallback, because if I use history api, links generated could be like /customers/5, though the fodler structure doesn't exist server side, its virtual. Then if I copy that link to another tab, you get 404. Thats why server side needs a general catch all to return index.html.

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.