Quantcast
Channel: node.js – webapplog [tech blog]
Viewing all articles
Browse latest Browse all 62

Express.js FUNdamentals

$
0
0

Express.js is an amazing framework for Node.js projects and used in the majority of such web apps. Unfortunately, there’s a lack of tutorials and examples on how to write good production-ready code. To mitigate this need, we released Express.js Guide: The Most Popular Node.js Framework Manual. However, all things start from basics, and for that reason we’ll give you a taste of the framework in this post, so you can decide if you want to continue the learning further.

Installation

Assuming you downloaded and installed Node.js (and NPM with it), run this command:

$ sudo npm install -g express@3.4.3

CLI

Now we can use command-line interface (CLI) to spawn new Express.js apps:

$ express -c styl expressfun
$ cd expressfun && npm install
$ node app

Open browser at http://localhost:3000.

Here is the full code of expressfun/app.js if you don’t have time to create an app right now:

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Routes

If you open the expressfun/app.js, you’ll see two routes in the middle:

...
app.get('/', routes.index);
app.get('/users', user.list);
...

The first one is basically takes care of all the requests to the home page, e.g., http://localhost:3000/ and the latter of requests to /users, such as http://localhost:3000/users. Both of the routes process URLs case insensitively and in a same manner as with trailing slashes.

The request handler itself (index.js in this case) is straightforward: every thing from the HTTP request is in req and write results to the response in res:

exports.list = function(req, res){
  res.send("respond with a resource");
};

Middleware

Each line above the routes is a middleware:

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

The middleware is a pass thru functions that add something useful to the request as it travels along each of them, for example req.body or req.cookie. For more middleware writings check out Intro to Express.js: Parameters, Error Handling and Other Middleware.

Configuration

Here is how we define configuration in a typical Express.js app:

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

An ordinary settings involves a name (e.g., views) and a value (e.g., path to the folder where out templates/views live). There are more than one way to define a certain settings, e.g, app.enable for boolean flags.

Jade

Jade template engine is akin to Ruby on Rails’ Haml in the way it uses whitespace and indentation, e.g., layout.jade:

doctype 5
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

Other than that, it’s possible to utilize full-blown JavaScript code inside of Jade templates.

Conslusion

As you’ve seen, it’s effortless to create MVC web apps with Express.js. The framework is splendid for REST APIs as well. If you interested in them, visit the Tutorial: Node.js and MongoDB JSON REST API server with Mongoskin and Express.js and Intro to Express.js: Simple REST API app with Monk and MongoDB.

If you want to know what are the other middlewares and configurations, check out Express.js API docs, Connect docs and of course our book — Express.js Guide. For those who already familiar with some basics of Express.js, I recommend going through ExpressWorks — an automated Express.js workshop.


Viewing all articles
Browse latest Browse all 62

Trending Articles