« Previous | 1 | 2 | 3 | Next »

Nodejs - Express Framework


Express Overview

Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node-based Web applications. Following are some of the core features of Express framework:
  • Allows to set up middlewares to respond to HTTP Requests.
  • Defines a routing table which is used to perform different actions based on HTTP Method and URL.
  • Allows to dynamically render HTML Pages based on passing arguments to templates.
Installing Express

Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal.

$ npm install express --save

The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express:
  • body-parser - This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
  • cookie-parser - Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
  • multer - This is a node.js middleware for handling multipart/form-data.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

Hello world Example

Following is a very basic Express app which starts a server and listens on port 3000 for connection. This app responds with Hello World! for requests to the homepage. For every other path, it will respond with a 404 Not Found.

var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Save the above code in a file named server.js and run it with the following command.

$ node server.js

You will see the following output:

Example app listening at http://0.0.0.0:8081

Open http://127.0.0.1:8081/ in any browser to see the following result.

Request & Response

Express application uses a callback function whose parameters are request and response objects.

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

  • Request Object - The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
  • Response Object - The response object represents the HTTP response that an Express app sends when it gets an HTTP request.
You can print req and res objects which provide a lot of information related to HTTP request and response including cookies, sessions, URL, etc.

Request Object

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.

Request Object Properties

Following is the list of few properties associated with request object.
S. No.Properties & Description
1req.app
This property holds a reference to the instance of the express application that is using the middleware.
2req.baseUrl
The URL path on which a router instance was mounted.
3req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser
4req.cookies
When using cookie-parser middleware, this property is an object that contains cookies sent by the request.
5req.fresh
Indicates whether the request is "fresh." It is the opposite of req.stale.
6req.hostname
Contains the hostname from the "Host" HTTP header.
7req.ip
The remote IP address of the request.
8req.ips
When the trust proxy setting is true, this property contains an array of IP addresses specified in the “X-Forwarded-For” request header.
9req.originalUrl
This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes.
10req.params
An object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the "name" property is available as req.params.name. This object defaults to {}.
11req.path
Contains the path part of the request URL.
12req.protocol
The request protocol string, "http" or "https" when requested with TLS.
13req.query
An object containing a property for each query string parameter in the route.
14req.route
The currently-matched route, a string.
15req.secure
A Boolean that is true if a TLS connection is established.
16req.signedCookies
When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use.
17req.stale
Indicates whether the request is "stale," and is the opposite of req.fresh.
18req.subdomains
An array of subdomains in the domain name of the request.
19req.xhr
A Boolean value that is true if the request’s "X-Requested-With" header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery
Request Object Methods

req.accepts(types)

req.accepts(types)

This method checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. Following are a few examples:

// Accept: text/html
req.accepts('html');
// => "html"
// Accept: text/*, application/json
req.accepts('html');
// => "html"
req.accepts('text/html');
// => "text/html"

req.get(field)

req.get(field)

This method returns the specified HTTP request header field. Following are a few examples:

req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined

req.is(type)

req.is(type)

This method returns true if the incoming request’s "Content-Type" HTTP header field matches the MIME type specified by the type parameter. Following are a few examples:

// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// => true

req.param(name [, defaultValue])

req.param(name [, defaultValue])

This method returns the value of param name when present. Following are few examples:

// ?name=tobi
req.param('name')
// => "tobi"
// POST name=tobi
req.param('name')
// => "tobi"
// /user/tobi for /user/:name
req.param('name')
// => "tobi"

Response Object

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

Response Object Properties

Following is the list of few properties associated with response object.
S. No.Properties & Description
1res.app
This property holds a reference to the instance of the express application that is using the middleware.
2res.headersSent
Boolean property that indicates if the app sent HTTP headers for the response.
3res.locals
An object that contains response local variables scoped to the request.
Response Object Methods

res.append(field [, value])

res.append(field [, value])

This method appends the specified value to the HTTP response header field. Following are a few examples:

res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
res.append('Warning', '199 Miscellaneous warning');

res.attachment([filename])

res.attachment([filename])

This method is used to send a file as an attachment in the HTTP response. Following are a few examples:

res.attachment('path/to/logo.png');

res.cookie(name, value [, options])

res.cookie(name, value [, options])

This method is used to set cookie name to value. The value parameter may be a string or object converted to JSON. Following are a few examples:

res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('cart', { items: [1,2,3] });
res.cookie('cart', { items: [1,2,3] }, { maxAge: 900000 });

res.clearCookie(name [, options])

res.clearCookie(name [, options])

This method is used to clear the cookie specified by name. Following are a few examples:

res.cookie('name', 'tobi', { path: '/admin' });
res.clearCookie('name', { path: '/admin' });

res.download(path [, filename] [, fn])

res.download(path [, filename] [, fn])

This method is used to transfer the file at path as an "attachment". Typically, browsers will prompt the user for download. Following are a few examples:

res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.download('/report-12345.pdf', 'report.pdf', function(err){
});

res.end([data] [, encoding])

res.end([data] [, encoding])

This method is used to end the response process. Following are a few examples:

res.end();
res.status(404).end();

res.format(object)

res.format(object)

This method is used to perform content-negotiation on the Accept HTTP header on the request object, when present. Following are a few examples:

'text/plain': function(){
res.send('hey');
},
'text/html': function(){
res.send('
hey
');
},
'application/json': function(){
res.send({ message: 'hey' });
},
'default': function() {
// log the request and respond with 406
res.status(406).send('Not Acceptable');
}
});

res.get(field)

res.get(field)

This method is used to return the HTTP response header specified by field. Here is an example:

res.get('Content-Type');

res.json([body])

res.json([body])

This method is used to send a JSON response. Following are a few examples:

res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })

res.jsonp([body])

res.jsonp([body])

This method is used to send a JSON response with JSONP support. Following are a few examples:

res.jsonp(null)
res.jsonp({ user: 'tobi' })
res.status(500).jsonp({ error: 'message' })

res.links(links)

res.links(links)

This method is used to join the links provided as properties of the parameter to populate the response’s Link HTTP header field. Following are a few examples:

res.links({
next: 'http://api.example.com/users?page=2',
last: 'http://api.example.com/users?page=5'
});

res.location(path)

res.location(path)

This method is used to set the response Location HTTP header field based on the specified path parameter. Following are a few examples:

res.location('/foo/bar');
res.location('foo/bar');
res.location('http://example.com');

res.redirect([status,] path)

res.redirect([status,] path)

This method is used to redirect to the URL dervied from the specified path, with specified HTTP status code status. Following are a few examples:

res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');

res.render(view [, locals] [, callback])

res.render(view [, locals] [, callback])

This method is used to render a view and sends the rendered HTML string to the client. Following are a few examples:

// send the rendered view to the client
res.render('index');
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
// ...
});

res.send([body])

res.send([body])

This method is used to send the HTTP response. Following are a few examples:

res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('
some html
');

res.sendFile(path [, options] [, fn])

res.sendFile(path [, options] [, fn])

This method is used to transfer the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension. Here is an example:

res.sendFile(fileName, options, function (err) {
// ...
});

res.sendStatus(statusCode)

res.sendStatus(statusCode)

This method is used to set the response HTTP status code to statusCode and send its string representation as the response body. Following are a few examples:

res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')

res.set(field [, value])

res.set(field [, value])

This method is used to set the response’s HTTP header field to value. Following are a few examples:

res.set('Content-Type', 'text/plain');
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})

res.status(code)

res.status(code)

This method is used to set the HTTP status for the response. Following are a few examples:

res.status(403).end();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/path/to/404.png');

res.type(type)

res.type(type)

This method is used to set the Content-Type HTTP header to the MIME type. Following are a few examples:

res.type('.html'); // => 'text/html'
res.type('html'); // => 'text/html'
res.type('json'); // => 'application/json'
res.type('application/json'); // => 'application/json'
res.type('png'); // => image/png:

Basic Routing

We have seen a basic application which serves HTTP request for the homepage. Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

We will extend our Hello World program to handle more types of HTTP requests.

var express = require('express');
var app = express();
// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Save the above code in a file named server.js and run it with the following command.

$ node server.js

You will see the following output:

Example app listening at http://0.0.0.0:8081

Now you can try different requests at http://127.0.0.1:8081 to see the output generated by server.js. Following are a few screenshots showing different responses for different URLs.

Screen showing again http://127.0.0.1:8081/list_user

Screen showing again http://127.0.0.1:8081/abcd

Screen showing again http://127.0.0.1:8081/abcdefg

Serving Static Files

Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc.

You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this:

app.use(express.static('public'));

We will keep a few images in public/images sub-directory as follows:

node_modules
server.js
public/
public/images
public/images/logo.png

Let's modify "Hello Word" app to add the functionality to handle static files.

var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Save the above code in a file named server.js and run it with the following command.

$ node server.js

Now open http://127.0.0.1:8081/images/logo.png in any browser and observe the following result.

GET Method

Here is a simple example which passes two values using HTML FORM GET method. We are going to use process_get router inside server.js to handle this input.

<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>

Let's save above code in index.htm and modify server.js to handle homepage requests as well as the input sent by the HTML form.

var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form:

First Name:
Last Name:

Now you can enter the First and Last Name and then click submit button to see the result and it should return the following result:

{"first_name":"John","last_name":"Paul"}

POST Method

Here is a simple example which passes two values using HTML FORM POST method. We are going to use process_get router inside server.js to handle this input.

<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>

Let's save the above code in index.htm and modify server.js to handle homepage requests as well as the input sent by the HTML form.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form:

File Upload:


Select a file to upload:

enctype="multipart/form-data">




This is just dummy form and would not work,but it must work at your server.

Now you can enter the First and Last Name and then click the submit button to see the following result:

{"first_name":"John","last_name":"Paul"}

File Upload

The following HTML code creates a file uploader form. This form has method attribute set to POST and enctype attribute is set to multipart/form-data

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://127.0.0.1:8081/file_upload" method="POST"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

Let's save above code in index.htm and modify server.js to handle homepage requests as well as file upload.

var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form:

File Upload:


Select a file to upload:

enctype="multipart/form-data">




NOTE: This is just dummy form and would not work,but it must work at your server.

Cookies Management

You can send cookies to a Node.js server which can handle the same using the following middleware option. Following is a simple example to print all the cookies sent by the client.

var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8081)
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com