הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Express Web Framework

So far we talked about Node as a tool to write web servers using the http module. Turns out beyond simple HTTP request/response, there's a lot of other code a web application needs. A Web Framework is a module that gives you the framework to write web applications.

In node there are several web frameworks, but the most popular one is called express. It's inspired by Sinatra and provides basic web applications boilerplate code such as:

  1. Routing
  2. Cookie and Session Management
  3. Serving Static Files
  4. Code Organization
  5. And More…

In the framework's web page you can find several projects powered by express, which include:

Hello Express

The exports object of express is a function, so to use it we require('express') and then run it to get an application. All our actions are performed on the returned application object.

Express implements routing a-la Sinatr, which means you define a route and a callback, and whenever a request arrives to that route, the callback is called. You can define as many routes as you want.

Inside a route callback, you can use the request and response object to get data about the request, and write back the response. send is a powerful method of the response object: It can send just about anything back to the client.

Start your server with app.listen(port).

var express = require('express');
var app = express();


app.get('/', function(req, res) {
  res.send('Hello Wrold');
});

app.listen(8080);

It's also possible to send files as a response to client's request. For example, this route sends a static file:

app.get('/logo.png', function(req, res) {
    res.sendfile('./public/images/logo.png');
});

Express Routes

Routes are defined by calling a method named after the various HTTP METHODS on the application object. The most interesting ones are:

  • app.get(…)
  • app.post(…)
  • app.put(…)
  • app.delete(...)

Note the code in each route handler should return as quickly as possible, to allow the server to respond to other clients as well (Remember, we only use a single thread here).

One nice feature express took from Sinatra is the ability to use named parameters as part of the route. Take the following example:

var express = require('express');
var app = express();


app.get('/user/:name', function(req, res) {
  var name = req.param('name');
  res.send('Hello ' + name );
});

app.listen(8080);

Using a named parameter as part of the route, each request to /user/value will assign value to the parameter named name. All these requests work:

# prints Hello me
 curl localhost:8080/user/me

 # prints Hello Dr
 curl localhost:8080/user/Dr

 # prints Hello Sir
 curl localhost:8080/user/Sir

You can also use param(name) to get the value of "normal" parameters, for both GET and POST parameters.

It's usually recommended to define route handlers in another module, require that module and use them when defining your routes.
Here's an example of using a different module to hold route handlers:

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

app.get('/user/:name', routes.hello );
app.listen(8080);

And in routes.js:

exports.hello = function( req, res ) {
  var name = req.param('name');
  res.send('Hello ' + name );
};

Error Handling

Express handles its routes using a pipeline. When a request arrives, it goes through all the chains in the pipeline until one is matched, and when that happens express runs the callback.

The last chain in the pipeline is the error handler. When a request arrives to the error chain, it simply returns an error code to the client.

The best way you can handle errors in your code is move the request up the pipeline to the next handler, and eventually it'll reach the error handler.

Each route handler is actually passed 3 arguments, the last one is a callback (usually named next). When you have an error, simply call the next callback with the error, and the error handler will handle it by sending an HTTP error code back to the client.

Here's a demo of a route that returns an error:

var express = require('express');
var app = express();

app.get('/error', function(req, res, next) {
  return next('Oh No...');
});

app.listen(8080);

For more information about express middleware pipeline, refer to the documentation.