0

I have a public folder in which I put an angular2 app. Now I am trying to setup an express server with a catchall route that always returns index.html. To be clear - according to this question I need to map all of my routes to index.html.

If I access the base server URL (localhost:10001), everything works as expected. But when I go to a route(let's say localhost:10001/landing), and refresh the page, I get the following error:

Error: ENOENT: no such file or directory, stat '/Users/shooshte/express-test/index.html' at Error (native)

This is my server configuration:

var express = require('express');
var static = require('serve-static');
var server = express();

// middleware
server.use(express.static(__dirname + '/public'));

// routes
server.use('*', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

var port = 10001;
server.listen(port, function() {
  console.log('server listening on port ' + port);
});

What am I doing wrong?

Community
  • 1
  • 1
Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163

2 Answers2

1

You're missing the public directory in the path to index.html:

 res.sendFile(__dirname + '/public/index.html');
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • thought this was already handled by the express.static part. Thanks – Miha Šušteršič May 06 '16 at 19:09
  • @MihaŠušteršič `express.static()` will only handle requests for which it can find a matching file. In your case, for `/landing`, it will try and find a file called `public/landing/index.html`, which doesn't exist (I assume). If it can't find a file it will delegate the request to the next handler, which is `server.use('*', ...)`. – robertklep May 07 '16 at 07:57
  • I have a related question. Are you willing to comment? Here is the link: http://stackoverflow.com/questions/38625483/error-enoent-no-such-file-or-directory-with-angular2-and-express-js – FirstOfMany Jul 28 '16 at 04:22
0

i think you don't have your index.html in either public or your root folder /Users/shooshte/express-test/

this is the only resion you are getting this error

Dinesh Agrawal
  • 326
  • 1
  • 3