Default route in Express.js

sublime picture sublime · Mar 26, 2014 · Viewed 47.6k times · Source

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>

Answer

jpgc picture jpgc · Mar 26, 2014

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.

Hope it helps.