28

I'm writing an application with node.js and express.

I have setup a default route as this :

app.get('/', function(req, res){
  res.sendfile('./views/index.html');
});

This works fine when I goto /localhost:port/

But in the URL when I type anything after that, /localhost:port/blah I get 404 ERROR which makes sense.

I want to setup a default route so that no matter what I type in the URL after localhost:port/ it should all get back the same html file.

I tried changing / to * :

app.get('*', function(req, res){
  res.sendfile('./views/index.html');
});

but after I do this I start getting this error in the console and nothing shows up:

Uncaught SyntaxError: Unexpected token <

in all of my Javascript files: :3000/scripts/myscript.js:1

somehow my javascript file show the content of HTML

===EDIT====

I used this and it worked fine for first level urls: like loclhost:port/blah

app.use(function(req, res){
    res.sendfile('./views/index.html');
});

but when the URLs are multilevel, I see the same problem as described earlier localhost:port/blah/foo The problem here is that router is looking for public directory under /blah folder for all the javascript and CSS files in this case, which does not exist. And it's returning the default HTML file. How do I fix this?

==================EDIT POSTING THE WHOLE CODE =========================================

var http = require('http');
var express = require('express');
var api = require('./routes/api');
var mongoose = require('mongoose');
var app = express();


mongoose.connect('mongodb://localhost/mydb');

app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);

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

app.get('/api/user/:userid', api.getUserInfo);

app.get('/', function(req, res){
  res.sendfile('./views/index.html');
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

In addition to this, I have an HTML with a myscript linked in it,

<script type="text/javascript" src="./scripts/myscript.js" ></script>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
sublime
  • 4,013
  • 9
  • 53
  • 92

3 Answers3

33

Add this route at the after of all your previous routes

app.get('*',function (req, res) {
        res.redirect('/');
    });

This will redirect any route not handled to the index "/"

dam1
  • 3,536
  • 3
  • 22
  • 18
  • This does work, but for some reason `request.url` always contains "/" instead of a full path which was specified. – humkins Apr 26 '17 at 08:56
28

As stated here, you can add this middleware just after your routing logic:

   app.use(function(req, res){
       res.send(404);
   });

You might find this answer also useful.

Of course, you need to adapt the res.send() part to meet your needs.

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
jpgc
  • 764
  • 5
  • 19
  • 1
    I added this app.use(function(req, res){ res.sendfile('./views/index.html'); }); and it worked for url/anything , but there is still a problem, when I type two levels in my url like localhost:port/anything/anything it throws up the same error as mentioned above. – sublime Mar 26 '14 at 21:53
  • ok the problem is when I say localhost:port/blah/anything, All the GET requests for javascript files are under /blah directory which does not exist, and so it is returning the HTML file. – sublime Mar 26 '14 at 22:01
4

With the newer version of express I would suggest using res.sendStatus as res.send has been deprecated.

Express v3

app.use(function(req, res){
   res.send(404);
});

Express v4

app.use(function(req, res){
   res.sendStatus(404);
});
Michael Warner
  • 3,879
  • 3
  • 21
  • 45
  • In Express 4.x you can also use `res.status(404).send('Sorry, we cannot find that!')` if you don't want to use the predefined status message for the status code ( `Not Found` in this case) – RubenLaguna Sep 18 '21 at 07:26