sublime sublime - 7 months ago 11
Node.js Question

Default route in Express.js

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

I have setup a default route as this :

app.get('/', function(req, res){

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){

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


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

app.use(function(req, res){

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();


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

app.use(express.cookieParser('your secret here'));

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

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

app.get('/', function(req, res){

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>


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

   app.use(function(req, res){

You might find this answer also useful.

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

Hope it helps.