Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default route in Express.js

Tags:

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> 
like image 674
sublime Avatar asked Mar 26 '14 21:03

sublime


People also ask

What is router () in Express?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express. js.

What is the default port for express JS?

I know that Express apps default to port 3000.

How does routing work in Express JS?

Routing with Express in Node: Express. js has an “app” object corresponding to HTTP. We define the routes by using the methods of this “app” object. This app object specifies a callback function, which is called when a request is received.

What are routes in node JS?

The route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), an URL path/pattern, and a function that is called to handle that pattern. Node. js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Node.


2 Answers

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 "/"

like image 173
dam1 Avatar answered Sep 28 '22 09:09

dam1


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.

like image 43
jpgc Avatar answered Sep 28 '22 09:09

jpgc