Error Handling In Express: Node.js

User inputs are very unpredictable on the web. So error handling becomes very important while building any real-time web application.

error-handling-in-express-nodejs

Express facilitates very good support for error handling, with its connect middleware.

Page Not Found Error Handling In Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res){
res.send(404, "Not found :-(");
});
 
app.get('/', function(req, res){
res.send("Homepage!");
});

When the user visits root of the website ( / ), a message called “Homepage!” is displayed to the user. But what if he tries to access a URL route which is not defined Ex: /user It displays Cannot GET /users message. We can set up a separate middleware to deal with situations like this. When we encounter a URL which doesn’t have a custom route definition, it’ll look for the file in the public directory, if the file is not found, it’ll look through our final middleware and executes whatever is present inside it.

User Not Found Error Handling In Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
app.use(function(err, req, res, next){
res.send(404, err.message);
next();
});
 
app.get('/user/:username', function(req, res, next){
if(req.params.username === 'kiran')
{
var err = new Error('User Not Found');
next(err);
}
res.send(req.params.username);
});

In real world application, we need to validate the user request before trying to serve them data. Here, if the user requests /user/kiran we’ll let the user know that the user kiran is not present in our database. So we setup a custom error handling middleware for situations like this. Here we create an error object and set a message, and pass this error object as parameter to next. call to next passes the control to the middleware which matches its signature, and executes whatever is present inside the middleware. [ Note the presence of err object inside the middleware callback method. ]

Error Handling In Express: Node.js


[youtube https://www.youtube.com/watch?v=noBowQTXSS4]

YouTube Link: https://www.youtube.com/watch?v=noBowQTXSS4 [Watch the Video In Full Screen.]



Note: Error handling can significantly increase the performance of your web application, due to the fact that your application need not figure out what to do next, in case of an error. You explicitly write error handling code for most common situations and the application behaves in a predictable manner.

Call to next() passes the execution control to the next level.

Middleware In Express: Node.js

We’ve been using middlewares in our previous video tutorials. Today, we’ll have a look at these middlewares.

middleware-connect-express-nodejs

Connect is a middleware framework of Node.js

But since connect is one of the dependencies of Express, we need not install it separately. If we have installed Express, then we already have connect.

Middeware in Express: Node.js
app.js

1
2
3
4
5
6
7
8
var express = require('express');
var app = express();
 app.use(express.bodyParser());
 app.use(express.methodOverride());
 app.use(express.cookieParser());
 app.use(express.session({secret: "some secret key"}));
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));

express.bodyParser extensible request body parser
express.methodOverride faux HTTP method support
express.cookieParser cookie parser
express.session session management support with bundled MemoryStore
express.static streaming static file server supporting Range and more
express.directory directory listing middleware

Middleware In Express: Node.js


[youtube https://www.youtube.com/watch?v=c4ScybD2690]

YouTube Link: https://www.youtube.com/watch?v=c4ScybD2690 [Watch the Video In Full Screen.]



For list of all supported middleware, visit senchalabs
Also check the list of all the 3rd-party middleware supported by Connect.

Note: Ordering of these middleware is very important.
For Example:
1. You can only override method after you’ve parsed the body, so methodOverride() must come only after bodyParser()
2. Similarly, session middleware depends on cookieParser(), so session middleware must come only after cookieParser()

As your application becomes popular you’ll need middlewares to handle csrf( Cross-site request forgery ), DDos attacks etc. Also it’s very important to validate the user requests before you allow the user request to fetch the data from your database. Learn to use middleware properly, and I’m sure, it’ll be a life-saver for your application.

Basic Routing Using Express: Node.js

Today let us learn a very important lesson in any web application development i.e., setting up the routes.

basic route using Express Node.js

Express is an excellent web framework for Node.js

Basic Routing with Express
app.js

1
2
3
app.get('/', function(req, res){
    res.send("Hello World!"); 
});

This would output Hello World when users access the index or home page.

Basic Routing with Express
app.js

1
2
3
app.get('/myPhone', function(req, res){
    res.send("Sony Xperia!"); 
});

This would output Sony Xperia! when users access the /myPhone route.

Dynamic Routing with Express
app.js

1
2
3
app.get('/user/:username', function(req, res){
    res.send(" "+req.params.username+"'s profile!"); 
});

When we request information of particular user by using his username in the URL, it fetches the username using request object and displays appropriate message.
Example: If the user requests /user/Satish it’ll output Satish’s profile!

Public Folder

If we put some files inside our public directory, it would be convenient if some middlewares fetch the files directly upon user request, instead of writing routes for all those files. Connect module which is a dependency of Express web framework takes care of this.

Middleware for public folder files
app.js

1
2
3
4
5
6
var express = require('express');
var path = require('path');
 
var app = express();
 
 app.use(express.static(path.join(__dirname, 'public')));

This would set the public directory.

Middleware for public folder files
app.js

1
2
 app.use(app.router);
 app.use(express.static(path.join(__dirname, 'public')));

If you want your custom routes to be checked before the public folder, then you could specify it using another middleware, i.e., app.router

Note that, the ordering of Middleware is significant.

Sending HTML in Routs: Express
app.js

1
2
3
4
5
6
7
8
9
10
app.get('/', function(req, res){
    var msg = [
               "<h1>I love Google..</h1>",
               "<p>Because they make awesome products",
               "<br />like my Nexus 7 Tablet",
               "which is so amazing!"
    ].join("\n");
    res.send(msg); 
});
</p>

This would out put with all HTML semantics on the browser.

Get, Post, Put, Delete Requests
Web browsers by default support only get and post requests. But we can override methods and make sure our Node.js application supports even the Put and Delete requests.

Post Request
HTML Form
index.html present in public directory

1
2
3
4
5
6
7
8
9
10
11
12
13
< !DOCTYPE html>
<html>
<head>
<title>Enter your name</title>
</head>
<body>
<form action="/user" method="POST">
<label for="name">Name: </label>
 <input type="text" name="name"/>
 <input type="submit"/>
</form>
</body>
</html>

Here we have a form with post method and also take note of action field value.

POST Route
app.js

1
2
3
4
5
app.use(express.bodyParser());
 
app.post('/user', function(req, res){
    res.send("Submitted user's name is: "+req.body.name);  
});

Inorder to parse the HTML page, you’ll need bodyParser middleware. Once you have it in place you can get form field entries and use it to insert the data into database or simply display as in our case with this example.

We could similarly write code for PUT and DELETE requests.
PUT & DELETE Routes
app.js

1
2
3
4
5
6
7
8
9
10
app.use(express.bodyParser());
app.use(express.methodOverride());
 
app.put('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});
 
app.delete('/user/:userId', function(req, res){
    res.send("Editing user with userid: "+req.params.userId);  
});

By getting the unique userId of the user, you could fetch the data from database and make changes and update the information using Put request. Similarly, using the unique userId of the user, you could select and delete the information about the user!

Basic Routing Using Express: Node.js


[youtube https://www.youtube.com/watch?v=zHykHw9JlhE]

YouTube Link: https://www.youtube.com/watch?v=zHykHw9JlhE [Watch the Video In Full Screen.]



Separating Route Files
As your application grows, its hard to keep the code cleaner and maintainable, so it’s always a good idea to separate these kind of information from the main application file. So we create a file called routes and include it as a local module in our main application file.

External Route File
/routes/index.js

1
2
3
4
5
6
7
/*
 * GET home page.
 */ 
exports.index = function(req, res){
  res.send('Google Nexus 5 To Be Release Shortly ..');
};

exports is a global provided by node.js
index is a name given by us; it’s a property name and we assign a function to it.

Accessing External Route File
app.js

1
2
3
var routes = require('./routes');
 
app.get('/', routes.index);

This would output: Google Nexus 5 To Be Release Shortly ..