Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy.
Express provides a thin layer of fundamental web application features, without obscuring Node features that you know and love.
Source: Express.js
Author of Express.js
Source: Express.js Hello World
$ npm install express --save
// FILENAME: app.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
$ node app.js
Example app listening at http://localhost:3000
Source: Routing
|
|
|
Source: Express API
app.METHOD(path, callback [, callback ...])
Source: Routing Paths
Path | Type | Params | Examples |
---|---|---|---|
"/path" | string pattern | /path | |
"/path/ab*cd" | string pattern | abcd, abxcd, abxxcd, abccd etc. | |
"/profile/:id" | string pattern | id | /profile/xxx, /profile/1234, /profile/abcd-1234 |
/\.md$/ | regular expression | /abcd.md, /path/1234.md; *NOT* match /abc.md/1234 |
Source: Routing Handlers
var cb0 = function (req, res, next) {
console.log('CB0');
next();
}
var cb1 = function (req, res, next) {
console.log('CB1');
next();
}
var cb2 = function (req, res) {
res.send('Hello from C!');
}
app.get('/example/c', [cb0, cb1], cb2);
// ROUTE - A
app.get('/', function(req, res) {
res.send('hello world');
});
// ROUTE - B
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});
// ROUTE - C
app.get('/about', function (req, res) {
res.send('about');
});
// ROUTE - D
app.get('/ab*cd', function(req, res) {
res.send('ab*cd');
});
// ROUTE - E
app.get(/.*fly$/, function(req, res) {
res.send('/.*fly$/');
});
// ROUTE - F
app.get('/path/:id', function(req, res) {
res.send('/path/' + req.params.id);
});
// ROUTE - G
app.post('/ab(cd)?e', function (req, res) {
res.send('ab(cd)?e');
});
// ROUTE - H
app.get('/example/b', function (req, res, next) {
console.log('response will be sent by' +
' the next function ...');
next();
}, function (req, res) {
res.send('Hello from B!');
});
Method | Description |
---|---|
res.download() | Prompt a file to be downloaded. |
res.end() | End the response process. |
res.json() | Send a JSON response. |
res.jsonp() | Send a JSON response with JSONP support. |
res.redirect() | Redirect a request. |
res.render() | Render a view template. |
res.send() | Send a response of various types. |
res.sendFile() | Send a file as an octet stream. |
res.sendStatus() | Set the response status code and send its string representation as the response body. |
Source: Routing
Source: Using Middleware
Source: Middleware Pattern
Source: Using Middleware
var app = express();
// a middleware with no mount path;
// gets executed for every request to the app
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
// a middleware mounted on /user/:id;
// will be executed for any type of HTTP request to /user/:id
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
// a route and its handler function (middleware system)
// which handles GET requests to /user/:id
app.get('/user/:id', function (req, res, next) {
res.send('USER');
});
Bind application-level middleware to an instance of the app object with app.use() and app.METHOD(), where METHOD is is the HTTP method of the request that it handles, such as GET, PUT, POST, and so on, in lowercase.
Source: Using Middleware
var app = express();
var router = express.Router();
// a middleware with no mount path, gets executed
// for every request to the router
router.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
// a middleware sub-stack shows request info for
// any type of HTTP request to /user/:id
router.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
Router-level middleware works just like application-level middleware except it is bound to an instance of express.Router().
// a middleware sub-stack which handles GET
// requests to /user/:id
router.get('/user/:id', function (req, res, next) {
// if user id is 0, skip to the next router
if (req.params.id == 0) next('route');
// else pass the control to the next middleware
// in this stack
else next();
}, function (req, res, next) {
// render a regular page
res.render('regular');
});
// handler for /user/:id which renders a special page
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id);
res.render('special');
});
// mount the router on the app
app.use('/', router);
Source: Using Middleware
Property | Description | Type | Default |
---|---|---|---|
dotfiles |
Option for serving dotfiles. Possible values are “allow”, “deny”, and “ignore” | String | “ignore” |
etag |
Enable or disable etag generation | Boolean | true |
extensions |
Sets file extension fallbacks. | Array | [] |
index |
Sends directory index file. Set false to disable directory indexing. |
Mixed | “index.html” |
lastModified |
Set the Last-Modified header to the last modified date of the file on the OS. Possible values are true or false . |
Boolean | true |
maxAge |
Set the max-age property of the Cache-Control header in milliseconds or a string in ms format | Number | 0 |
redirect |
Redirect to trailing “/” when the pathname is a directory. | Boolean | true |
setHeaders |
Function for setting HTTP headers to serve with the file. | Function |
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
}
}
app.use(express.static('public', options));
Source: Third-Party Middlewares
$ npm install cookie-parser
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
// load the cookie parsing middleware
app.use(cookieParser());
WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.
The WebSocket API is a Candidate Recommendation of W3C standard.
Source: Wikipedia - WebSocket
Source:
var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']);
// When the connection is open, send some data to the server
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
// Sending String
connection.send('your message');
Source: RFC6455
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
Source: RFC6455
Source: WS
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
Source: Why Use Node.js
Source: RESTful Web Services
Source: RESTful Web Services
Source: RESTful Web Services
Source: RESTful Web Services
Stateful Web Service
Stateless Web Service
http://www.myservice.org/discussion/{year}/{day}/{month}/{topic}
Source: RESTful Web Services
MIME-Type | Content-Type |
---|---|
JSON | application/json |
XML | application/xml |
XHTML | application/xhtml+xml |
Source: RESTful Web Services
Source: Why Git?