1

I've seen plenty of posts tackling this issue but none seem to work for me and many solutions use deprecated methods.

I have static file directory already set up:

app.use(express.static(__dirname + "/public", {maxAge: 86400000*30 }));

Then I have a custom 404.html page in that public directory. Now, any incorrect URLs should be routed to that 404.html page. I've tried the following:

app.use(function(req, res, next){
  res.render("404.html", { url: req.url });
});

But I get the response:

Error: Cannot find module 'html'

What am I doing wrong and why is such a simple thing so hard?

CaribouCode
  • 13,998
  • 28
  • 102
  • 174
  • Express expect to have a renderer for all file types, even static ones like HTML. See this answer for more info: http://stackoverflow.com/a/4531225/502126 – Henrik Karlsson Jan 03 '15 at 12:44
  • If you're using 404.html as a template, what kind of template is it? ejs? jade? handlebars? Something else? Or is it really not a template and you just want to display the static content if no route handler matches? – mscdex Jan 03 '15 at 14:20
  • @mscdex It's just a regular html page, no template or dynamic content in it. Not using jade or ejs or anything like that. The same way my app also servers the index.html as a regular html page because Express points to the public folder. – CaribouCode Jan 03 '15 at 14:27

2 Answers2

3

Just put something like this after all of your other middleware and route handlers:

app.use(function(req, res) {
  res.sendFile(__dirname + '/public/404.html');
});
mscdex
  • 104,356
  • 15
  • 192
  • 153
1

Try upgrading your version of express to latest

Edited (corrected version from @mscdex)

app.get('/api', function(req, res) {
   .....
   res.status(404).sendFile(__dirname + '/public/404.html');
});

http://expressjs.com/api.html#res.status

Prabhakar Kasi
  • 531
  • 4
  • 18
  • I am using Express 4.7.2. It is a very recent release. How will upgrading it further help me with 404 routing? – CaribouCode Jan 03 '15 at 16:19
  • I don't enough reputation to comment on the post. My response was to your comment "I get TypeError: Object # has no method 'sendFile'" from @mscdex reply – Prabhakar Kasi Jan 03 '15 at 16:22
  • 1
    That seems to work now, I had to also put the code snippet below all my API routes otherwise they just did nothing. Thanks – CaribouCode Jan 03 '15 at 16:38