Vous êtes sur la page 1sur 48

Table

of Contents
1. Introduction
2. Expressjs
3. Middleware
i. errorhandler
ii. session
iii. compression
iv. morgan
v. cookie-parser
vi. serve-favicon
vii. express-session
viii. response-time
ix. serve-static
x. serve-index
xi. csurf
xii. vhost
xiii. connect-timeout
xiv. method-override
xv. multer
xvi. body-parser
Expressjs 4 and his middleware
This (git)book recopilate all of Readme.md of all expressjs middleware. We wish this book are very useful for express
developers.

View the summary and read anymore!

Regards,
Mario Martínez (ewiggin)
Fast, unopinionated, minimalist web framework for node.

npm v4.10.6 downloads 2M/month


build pending coverage 100%

var express = require('express')


var app = express()

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


res.send('Hello World')
})

app.listen(3000)

Installation

$ npm install express

Features
Robust routing
Focus on high performance
Super-high test coverage
HTTP helpers (redirection, caching, etc)
View system supporting 14+ template engines
Content negotiation
Executable for generating applications quickly

Docs & Community


Website and Documentation - [website repo]
#express on freenode IRC
Github Organization for Official Middleware & Modules
Visit the Wiki
Google Group for discussion
Русскоязычная документация
한국어 문서 - [website repo]

PROTIP Be sure to read Migrating from 3.x to 4.x as well as New features in 4.x.

Quick Start
The quickest way to get started with express is to utilize the executable express(1) to generate an application as shown
below:

Install the executable. The executable's major version will match Express's:
$ npm install -g express-generator@4

Create the app:

$ express /tmp/foo && cd /tmp/foo

Install dependencies:

$ npm install

Start the server:

$ npm start

Philosophy
The Express philosophy is to provide small, robust tooling for HTTP servers, making it a great solution for single page
applications, web sites, hybrids, or public HTTP APIs.

Express does not force you to use any specific ORM or template engine. With support for over 14 template engines via
Consolidate.js, you can quickly craft your perfect framework.

Examples
To view the examples, clone the Express repo & install the dependancies:

$ git clone git://github.com/strongloop/express.git --depth 1


$ cd express
$ npm install

Then run whichever example you want:

$ node examples/content-negotiation

Tests
To run the test suite, first install the dependancies, then run npm test :

$ npm install
$ npm test

People

The original author of Express is TJ Holowaychuk tips $33/week

The current lead maintainer is Douglas Christopher Wilson tips $10/week


List of all contributors

License

MIT
Middleware
errorhandler
npm v1.3.0 downloads 799k/month build passing coverage 100% tips $10/week

Development-only error handler middleware

Install

$ npm install errorhandler

API

var errorhandler = require('errorhandler')

errorhandler([options])

Create new middleware to handle errors and respond with content negotiation. This middleware is only intended to be used
in a development environment, as the full error stack traces will be sent back to the client when an error occurs.

options.log

Provide a function to be called with the error and a string representation of the error. Can be used to write the error to any
desired location, or set to false to only send the error back in the response. Called as log(err, str, req, res) where
err is the Error object, str is a string representation of the error, req is the request object and res is the response

object (note, this function is invoked after the response has been written).

The default value for this option is true unless process.env.NODE_ENV === 'test' .

Possible values:

true : Log errors using console.error(str) .

false : Only send the error back in the response.

A function: pass the error to a function for handling.

Examples

Simple example

Basic example of adding this middleware as the error handler only in development with connect ( express also can be
used in this example).

var connect = require('connect')


var errorhandler = require('errorhandler')

var app = connect()

if (process.env.NODE_ENV === 'development') {


// only use in development
app.use(errorhandler())
}
Custom output location

Sometimes you may want to output the errors to a different location than STDERR during development, like a system
notification, for example.

var connect = require('connect')


var errorhandler = require('errorhandler')
var notifier = require('node-notifier')

var app = connect()

if (process.env.NODE_ENV === 'development') {


// only use in development
app.use(errorhandler({log: errorNotification}))
}

function errorNotification(err, str, req) {


var title = 'Error in ' + req.method + ' ' + req.url

notifier.notify({
title: title,
message: str
})
}

License
MIT
express-session
npm v1.9.3 downloads 884k/month build passing coverage 100% tips $10/week

Installation

$ npm install express-session

API

var express = require('express')


var session = require('express-session')

var app = express()

app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))

session(options)

Setup session store with the given options .

Session data is not saved in the cookie itself, just the session ID.

Options

name - cookie name (formerly known as key ). (default: 'connect.sid' )

store - session store instance.

secret - session cookie is signed with this secret to prevent tampering.

cookie - session cookie settings.

(default: { path: '/', httpOnly: true, secure: false, maxAge: null } )


genid - function to call to generate a new session ID. (default: uses uid2 library)

rolling - forces a cookie set on every response. This resets the expiration date. (default: false )

resave - forces session to be saved even when unmodified. (default: true , but using the default has been

deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to
your use-case. Typically, you'll want false )
proxy - trust the reverse proxy when setting secure cookies (via "x-forwarded-proto" header). When set to true , the

"x-forwarded-proto" header will be used. When set to false , all headers are ignored. When left unset, will use the
"trust proxy" setting from express. (default: undefined )
saveUninitialized - forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is

new but not modified. (default: true , but using the default has been deprecated, as the default will change in the
future. Please research into this setting and choose what is appropriate to your use-case)
unset - controls result of unsetting req.session (through delete , setting to null , etc.). This can be "keep" to keep

the session in the store but ignore modifications or "destroy" to destroy the stored session. (default: 'keep' )

options.genid

Generate a custom session ID for new sessions. Provide a function that returns a string that will be used as a session ID.
The function is given req as the first argument if you want to use some value attached to req when generating the ID.
NOTE be careful you generate unique IDs so your sessions do not conflict.

app.use(session({
genid: function(req) {
return genuuid(); // use UUIDs for session IDs
},
secret: 'keyboard cat'
}))

options.resave

Forces the session to be saved back to the session store, even if the session was never modified during the request.
Depending on your store this may be necessary, but it can also create race conditions where a client has two parallel
requests to your server and changes made to the session in one request may get overwritten when the other request ends,
even if it made no changes (this behavior also depends on what store you're using).

options.saveUninitialized

Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified.
Choosing false is useful for implementing login sessions, reducing server storage usage, or complying with laws that
require permission before setting a cookie. Choose false will also help with race conditions where a client makes multiple
parallel requests without a session.

Cookie options

Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is
necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set. If you have
your node.js behind a proxy and are using secure: true , you need to set "trust proxy" in express:

var app = express()


app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))

For using secure cookies in production, but allowing for testing in development, the following is an example of enabling this
setup based on NODE_ENV in express:

var app = express()


var sess = {
secret: 'keyboard cat',
cookie: {}
}

if (app.get('env') === 'production') {


app.set('trust proxy', 1) // trust first proxy
sess.cookie.secure = true // serve secure cookies
}

app.use(session(sess))

By default cookie.maxAge is null , meaning no "expires" parameter is set so the cookie becomes a browser-session
cookie. When the user closes the browser the cookie (and session) will be removed.

req.session

To store or access session data, simply use the request property req.session , which is (generally) serialized as JSON by
the store, so nested objects are typically fine. For example below is a user-specific view counter:

app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))

app.use(function(req, res, next) {


var sess = req.session
if (sess.views) {
sess.views++
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' + sess.views + '</p>')
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
sess.views = 1
res.end('welcome to the session demo. refresh!')
}
})

Session.regenerate()

To regenerate the session simply invoke the method, once complete a new SID and Session instance will be initialized at
req.session .

req.session.regenerate(function(err) {
// will have a new session here
})

Session.destroy()

Destroys the session, removing req.session , will be re-generated next request.

req.session.destroy(function(err) {
// cannot access session here
})

Session.reload()

Reloads the session data.

req.session.reload(function(err) {
// session updated
})

Session.save()

req.session.save(function(err) {
// session saved
})

Session.touch()

Updates the .maxAge property. Typically this is not necessary to call, as the session middleware does this for you.

req.session.cookie

Each session has a unique cookie object accompany it. This allows you to alter the session cookie per visitor. For example
we can set req.session.cookie.expires to false to enable the cookie to remain for only the duration of the user-agent.
Cookie.maxAge

Alternatively req.session.cookie.maxAge will return the time remaining in milliseconds, which we may also re-assign a new
value to adjust the .expires property appropriately. The following are essentially equivalent

var hour = 3600000


req.session.cookie.expires = new Date(Date.now() + hour)
req.session.cookie.maxAge = hour

For example when maxAge is set to 60000 (one minute), and 30 seconds has elapsed it will return 30000 until the current
request has completed, at which time req.session.touch() is called to reset req.session.maxAge to its original value.

req.session.cookie.maxAge // => 30000

Session Store Implementation


Every session store must implement the following methods

.get(sid, callback)

.set(sid, session, callback)

.destroy(sid, callback)

Recommended methods include, but are not limited to:

.length(callback)

.clear(callback)

For an example implementation view the connect-redis repo.

License
MIT
morgan
npm v1.5.0 downloads 978k/month build passing coverage 100% tips $10/week

HTTP request logger middleware for node.js

Named after Dexter, a show you should not watch until completion.

API

var morgan = require('morgan')

morgan(format, options)

Create a new morgan logger middleware function using the given format and options . The format argument may be a
string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry.

Options

Morgan accepts these properties in the options object.

immediate

Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data
from the response (like the response code, content length, etc.) cannot be logged.

skip

Function to determine if logging is skipped, defaults to false . This function will be called as skip(req, res) .

// EXAMPLE: only log error responses


morgan('combined', {
skip: function (req, res) { return res.statusCode < 400 }
})

stream

Output stream for writing log lines, defaults to process.stdout .

Predefined Formats

There are various pre-defined formats provided:

combined

Standard Apache combined log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"

common
Standard Apache common log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]

dev

Concise output colored by response status for development use. The :status token will be colored red for server error
codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes.

:method :url :status :response-time ms - :res[content-length]

short

Shorter than default, also including response time.

:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms

tiny

The minimal output.

:method :url :status :res[content-length] - :response-time ms

Tokens

Creating new tokens

To define a token, simply invoke morgan.token() with the name and a callback function. This callback function is expected
to return a string value. The value returned is then available as ":type" in this case:

morgan.token('type', function(req, res){ return req.headers['content-type']; })

Calling morgan.token() using the same name as an existing token will overwrite that token definition.

:date[format]

The current date and time in UTC. The available formats are:

clf for the common log format ( "10/Oct/2000:13:55:36 +0000" )

iso for the common ISO 8601 date time format ( 2000-10-10T13:55:36.000Z )

web for the common RFC 1123 date time format ( Tue, 10 Oct 2000 13:55:36 GMT )

If no format is given, then the default is web .

:http-version

The HTTP version of the request.

:method

The HTTP version of the request.

:referrer
The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.

:remote-addr

The remote address of the request. This will use req.ip , otherwise the standard req.connection.remoteAddress value
(socket address).

:remote-user

The user authenticated as part of Basic auth for the request.

:req[header]

The given header of the request.

:res[header]

The given header of the response.

:response-time

The time between the request coming into morgan and when the response headers are written, in milliseconds.

:status

The status code of the response.

:url

The URL of the request. This will use req.originalUrl if exists, otherwise req.url .

:user-agent

The contents of the User-Agent header of the request.

Examples

express/connect

Simple app that will log all request in the Apache combined format to STDOUT

var express = require('express')


var morgan = require('morgan')

var app = express()

app.use(morgan('combined'))

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


res.send('hello, world!')
})

vanilla http server

Simple app that will log all request in the Apache combined format to STDOUT

var finalhandler = require('finalhandler')


var http = require('http')
var morgan = require('morgan')

// create "middleware"
var logger = morgan('combined')
http.createServer(function (req, res) {
var done = finalhandler(req, res)
logger(req, res, function (err) {
if (err) return done(err)

// respond to request
res.setHeader('content-type', 'text/plain')
res.end('hello, world!')
})
})

write logs to a file

Simple app that will log all request in the Apache combined format to the file "access.log"

var express = require('express')


var fs = require('fs')
var morgan = require('morgan')

var app = express()

// create a write stream (in append mode)


var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})

// setup the logger


app.use(morgan('combined', {stream: accessLogStream}))

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


res.send('hello, world!')
})

use custom token formats

Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.

var express = require('express')


var morgan = require('morgan')
var uuid = require('node-uuid')

morgan.token('id', function getId(req) {


return req.id
})

var app = express()

app.use(assignId)
app.use(morgan(':id :method :url :response-time'))

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


res.send('hello, world!')
})

function assignId(req, res, next) {


req.id = uuid.v4()
next()
}

License
MIT
cookie-parser
npm v1.3.3 downloads 840k/month build passing coverage 100%

Parse Cookie header and populate req.cookies with an object keyed by the cookie names. Optionally you may enable
signed cookie support by passing a secret string, which assigns req.secret so it may be used by other middleware.

Installation

$ npm install cookie-parser

API

var express = require('express')


var cookieParser = require('cookie-parser')

var app = express()


app.use(cookieParser())

cookieParser(secret, options)

secret a string used for signing cookies. This is optional and if not specified, will not parse signed cookies.

options an object that is passed to cookie.parse as the second option. See cookie for more information.

decode a function to decode the value of the cookie

cookieParser.JSONCookie(str)

Parse a cookie value as a JSON cookie. This will return the parsed JSON value if it was a JSON cookie, otherwise it will
return the passed value.

cookieParser.JSONCookies(cookies)

Given an object, this will iterate over the keys and call JSONCookie on each value. This will return the same object passed
in.

cookieParser.signedCookie(str, secret)

Parse a cookie value as a signed cookie. This will return the parsed unsigned value if it was a signed cookie and the
signature was valid, otherwise it will return the passed value.

cookieParser.signedCookies(cookies, secret)

Given an object, this will iterate over the keys and check if any value is a signed cookie. If it is a signed cookie and the
signature is valid, the key will be deleted from the object and added to the new object that is returned.

Example

var express = require('express')


var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())

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


console.log("Cookies: ", req.cookies)
})

app.listen(8080)

// curl command that sends an HTTP request with two cookies


// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"

MIT Licensed
serve-favicon
npm v2.2.0 downloads 787k/month build passing coverage 100% tips $10/week

Node.js middleware for serving a favicon.

Why use this module?

User agents request favicon.ico frequently and indiscriminately, so you may wish to exclude these requests from
your logs by using this middleware before your logger middleware.
This module caches the icon in memory to improve performance by skipping disk access.
This module provides an ETag based on the contents of the icon, rather than file system properties.
This module will serve with the most compatible Content-Type .

Install

npm install serve-favicon

API

favicon(path, options)

Create new middleware to serve a favicon from the given path to a favicon file. path may also be a Buffer of the icon to
serve.

Options

Serve favicon accepts these properties in the options object.

maxAge

The cache-control max-age directive in ms , defaulting to 1 day. This can also be a string accepted by the ms module.

Examples
Typically this middleware will come very early in your stack (maybe even first) to avoid processing any other middleware if
we already know the request is for /favicon.ico .

express

var express = require('express');


var favicon = require('serve-favicon');

var app = express();


app.use(favicon(__dirname + '/public/favicon.ico'));

// Add your routes here, etc.

app.listen(3000);

connect
var connect = require('connect');
var favicon = require('serve-favicon');

var app = connect();


app.use(favicon(__dirname + '/public/favicon.ico'));

// Add your middleware here, etc.

app.listen(3000);

vanilla http server

This middleware can be used anywhere, even outside express/connect. It takes req , res , and callback .

var http = require('http');


var favicon = require('serve-favicon');
var finalhandler = require('finalhandler');

var _favicon = favicon(__dirname + '/public/favicon.ico');

var server = http.createServer(function onRequest(req, res) {


var done = finalhandler(req, res);

_favicon(req, res, function onNext(err) {


if (err) return done(err);

// continue to process the request here, etc.

res.statusCode = 404;
res.end('oops');
});
});

server.listen(3000);

License
MIT
express-session
npm v1.9.3 downloads 884k/month build passing coverage 100% tips $10/week

Installation

$ npm install express-session

API

var express = require('express')


var session = require('express-session')

var app = express()

app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))

session(options)

Setup session store with the given options .

Session data is not saved in the cookie itself, just the session ID.

Options

name - cookie name (formerly known as key ). (default: 'connect.sid' )

store - session store instance.

secret - session cookie is signed with this secret to prevent tampering.

cookie - session cookie settings.

(default: { path: '/', httpOnly: true, secure: false, maxAge: null } )


genid - function to call to generate a new session ID. (default: uses uid2 library)

rolling - forces a cookie set on every response. This resets the expiration date. (default: false )

resave - forces session to be saved even when unmodified. (default: true , but using the default has been

deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to
your use-case. Typically, you'll want false )
proxy - trust the reverse proxy when setting secure cookies (via "x-forwarded-proto" header). When set to true , the

"x-forwarded-proto" header will be used. When set to false , all headers are ignored. When left unset, will use the
"trust proxy" setting from express. (default: undefined )
saveUninitialized - forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is

new but not modified. (default: true , but using the default has been deprecated, as the default will change in the
future. Please research into this setting and choose what is appropriate to your use-case)
unset - controls result of unsetting req.session (through delete , setting to null , etc.). This can be "keep" to keep

the session in the store but ignore modifications or "destroy" to destroy the stored session. (default: 'keep' )

options.genid

Generate a custom session ID for new sessions. Provide a function that returns a string that will be used as a session ID.
The function is given req as the first argument if you want to use some value attached to req when generating the ID.
NOTE be careful you generate unique IDs so your sessions do not conflict.

app.use(session({
genid: function(req) {
return genuuid(); // use UUIDs for session IDs
},
secret: 'keyboard cat'
}))

options.resave

Forces the session to be saved back to the session store, even if the session was never modified during the request.
Depending on your store this may be necessary, but it can also create race conditions where a client has two parallel
requests to your server and changes made to the session in one request may get overwritten when the other request ends,
even if it made no changes (this behavior also depends on what store you're using).

options.saveUninitialized

Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified.
Choosing false is useful for implementing login sessions, reducing server storage usage, or complying with laws that
require permission before setting a cookie. Choose false will also help with race conditions where a client makes multiple
parallel requests without a session.

Cookie options

Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is
necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set. If you have
your node.js behind a proxy and are using secure: true , you need to set "trust proxy" in express:

var app = express()


app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))

For using secure cookies in production, but allowing for testing in development, the following is an example of enabling this
setup based on NODE_ENV in express:

var app = express()


var sess = {
secret: 'keyboard cat',
cookie: {}
}

if (app.get('env') === 'production') {


app.set('trust proxy', 1) // trust first proxy
sess.cookie.secure = true // serve secure cookies
}

app.use(session(sess))

By default cookie.maxAge is null , meaning no "expires" parameter is set so the cookie becomes a browser-session
cookie. When the user closes the browser the cookie (and session) will be removed.

req.session

To store or access session data, simply use the request property req.session , which is (generally) serialized as JSON by
the store, so nested objects are typically fine. For example below is a user-specific view counter:

app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))

app.use(function(req, res, next) {


var sess = req.session
if (sess.views) {
sess.views++
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' + sess.views + '</p>')
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
sess.views = 1
res.end('welcome to the session demo. refresh!')
}
})

Session.regenerate()

To regenerate the session simply invoke the method, once complete a new SID and Session instance will be initialized at
req.session .

req.session.regenerate(function(err) {
// will have a new session here
})

Session.destroy()

Destroys the session, removing req.session , will be re-generated next request.

req.session.destroy(function(err) {
// cannot access session here
})

Session.reload()

Reloads the session data.

req.session.reload(function(err) {
// session updated
})

Session.save()

req.session.save(function(err) {
// session saved
})

Session.touch()

Updates the .maxAge property. Typically this is not necessary to call, as the session middleware does this for you.

req.session.cookie

Each session has a unique cookie object accompany it. This allows you to alter the session cookie per visitor. For example
we can set req.session.cookie.expires to false to enable the cookie to remain for only the duration of the user-agent.
Cookie.maxAge

Alternatively req.session.cookie.maxAge will return the time remaining in milliseconds, which we may also re-assign a new
value to adjust the .expires property appropriately. The following are essentially equivalent

var hour = 3600000


req.session.cookie.expires = new Date(Date.now() + hour)
req.session.cookie.maxAge = hour

For example when maxAge is set to 60000 (one minute), and 30 seconds has elapsed it will return 30000 until the current
request has completed, at which time req.session.touch() is called to reset req.session.maxAge to its original value.

req.session.cookie.maxAge // => 30000

Session Store Implementation


Every session store must implement the following methods

.get(sid, callback)

.set(sid, session, callback)

.destroy(sid, callback)

Recommended methods include, but are not limited to:

.length(callback)

.clear(callback)

For an example implementation view the connect-redis repo.

License
MIT
response-time
npm v2.2.0 downloads 703k/month build passing coverage 100% tips $10/week

Response time header for node.js

Installation

$ npm install response-time

API

var responseTime = require('response-time')

responseTime(options)

Returns middleware that adds a X-Response-Time header to responses.

Options

responseTime accepts these properties in the options object.

digits

The fixed number of digits to include in the output, which is always in milliseconds, defaults to 3 (ex: 2.300ms ).

header

The name of the header to set, defaults to X-Response-Time .

suffix

Boolean to indicate if units of measurement suffix should be added to the output, defaults to true (ex: 2.300ms vs 2.300 ).

Examples

express/connect

var express = require('express')


var responseTime = require('response-time')

var app = express()

app.use(responseTime())

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


res.send('hello, world!')
})

vanilla http server


var finalhandler = require('finalhandler')
var http = require('http')
var responseTime = require('response-time')

// create "middleware"
var _responseTime = responseTime()

http.createServer(function (req, res) {


var done = finalhandler(req, res)
_responseTime(req, res, function (err) {
if (err) return done(err)

// respond to request
res.setHeader('content-type', 'text/plain')
res.end('hello, world!')
})
})

License
MIT
serve-static
npm v1.7.1 downloads 1M/month build passing coverage 100% tips $10/week

Install

$ npm install serve-static

API

var serveStatic = require('serve-static')

serveStatic(root, options)

Create a new middleware function to serve files from within a given root directory. The file to serve will be determined by
combining req.url with the provided root directory. When a file is not found, instead of sending a 404 response, this
module will instead call next() to move on to the next middleware, allowing for stacking and fall-backs.

Options

dotfiles

Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). Note this check is
done on the path itself without checking if the path actually exists on the disk. If root is specified, only the dotfiles above
the root are checked (i.e. the root itself can be within a dotfile when when set to "deny").

The default value is 'ignore' .

'allow' No special treatment for dotfiles.

'deny' Send a 403 for any request for a dotfile.

'ignore' Pretend like the dotfile does not exist and call next() .

etag

Enable or disable etag generation, defaults to true.

extensions

Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search
for. The first that exists will be served. Example: ['html', 'htm'] .

The default value is false .

index

By default this module will send "index.html" files in response to a request on a directory. To disable this set false or to
supply a new index pass a string or an array in preferred order.

lastModified

Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value.
maxAge

Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module.

redirect

Redirect to trailing "/" when the pathname is a dir. Defaults to true .

setHeaders

Function to set custom headers on response. Alterations to the headers need to occur synchronously. The function is called
as fn(res, path, stat) , where the arguments are:

res the response object

path the file path that is being sent

stat the stat object of the file that is being sent

Examples

Serve files with vanilla node.js http server

var finalhandler = require('finalhandler')


var http = require('http')
var serveStatic = require('serve-static')

// Serve up public/ftp folder


var serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']})

// Create server
var server = http.createServer(function(req, res){
var done = finalhandler(req, res)
serve(req, res, done)
})

// Listen
server.listen(3000)

Serve all files as downloads

var contentDisposition = require('content-disposition')


var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

// Serve up public/ftp folder


var serve = serveStatic('public/ftp', {
'index': false,
'setHeaders': setHeaders
})

// Set header to force download


function setHeaders(res, path) {
res.setHeader('Content-Disposition', contentDisposition(path))
}

// Create server
var server = http.createServer(function(req, res){
var done = finalhandler(req, res)
serve(req, res, done)
})

// Listen
server.listen(3000)

Serving using express


var connect = require('connect')
var serveStatic = require('serve-static')

var app = connect()

app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']}))


app.listen(3000)

License
MIT
serve-index
npm v1.5.3 downloads 826k/month build passing coverage 100% tips $10/week

Serves pages that contain directory listings for a given path.

Install

$ npm install serve-index

API

var serveIndex = require('serve-index')

serveIndex(path, options)

Returns middlware that serves an index of the directory in the given path .

The path is based off the req.url value, so a req.url of '/some/dir with a path of 'public' will look at
'public/some/dir' . If you are using something like express , you can change the URL "base" with app.use (see the

express example).

Options

Serve index accepts these properties in the options object.

filter

Apply this filter function to files. Defaults to false . The filter function is called for each file, with the signature
filter(filename, index, files, dir) where filename is the name of the file, index is the array index, files is the array

of files and dir is the absolute path the file is located (and thus, the directory the listing is for).

hidden

Display hidden (dot) files. Defaults to false .

icons

Display icons. Defaults to false .

stylesheet

Optional path to a CSS stylesheet. Defaults to a built-in stylesheet.

template

Optional path to an HTML template. Defaults to a built-in template.

The following tokens are replaced in templates:

{directory} with the name of the directory.

{files} with the HTML of an unordered list of file links.


{linked-path} with the HTML of a link to the directory.

{style} with the specified stylesheet and embedded images.

view

Display mode. tiles and details are available. Defaults to tiles .

Examples

Serve directory indexes with vanilla node.js http server

var finalhandler = require('finalhandler')


var http = require('http')
var serveIndex = require('serve-index')
var serveStatic = require('serve-static')

// Serve directory indexes for public/ftp folder (with icons)


var index = serveIndex('public/ftp', {'icons': true})

// Serve up public/ftp folder files


var serve = serveStatic('public/ftp')

// Create server
var server = http.createServer(function onRequest(req, res){
var done = finalhandler(req, res)
serve(req, res, function onNext(err) {
if (err) return done(err)
index(req, res, done)
})
})

// Listen
server.listen(3000)

Serve directory indexes with express

var express = require('express')


var serveIndex = require('serve-index')

var app = express()

// Serve URLs like /ftp/thing as public/ftp/thing


app.use('/ftp', serveIndex('public/ftp', {'icons': true}))
app.listen()

License
MIT. The Silk icons are created by/copyright of FAMFAMFAM.
csurf
npm v1.6.3 downloads 701k/month build passing coverage 100%

Node.js CSRF protection middleware.

Requires either a session middleware or cookie-parser to be initialized first.

session
cookie-session

Install

$ npm install csurf

API

var csrf = require('csurf')

csrf(options)

This middleware adds a req.csrfToken() function to make a token which should be added to requests which mutate state,
within a hidden form field, query-string etc. This token is validated against the visitor's session or csrf cookie.

Options

value a function accepting the request, returning the token.

The default function checks four possible token locations:


_csrf parameter in req.body generated by the body-parser middleware.

_csrf parameter in req.query generated by query() .

x-csrf-token and x-xsrf-token header fields.

cookie set to a truthy value to enable cookie-based instead of session-based csrf secret storage.

If cookie is an object, these options can be configured, otherwise defaults are used:
key the name of the cookie to use (defaults to _csrf ) to store the csrf secret

any other res.cookie options can be set


ignoreMethods An array of the methods CSRF token checking will disabled. (default: ['GET', 'HEAD', 'OPTIONS'] )

req.csrfToken()

Lazy-loads the token associated with the request.

Example

Simple express example

The following is an example of some server-side code that protects all non-GET/HEAD/OPTIONS routes with a CSRF
token.

var express = require('express')


var csrf = require('csurf')
var app = express()
app.use(csrf())

// error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)

// handle CSRF token errors here


res.status(403)
res.send('session has expired or form tampered with')
})

// pass the csrfToken to the view


app.get('/form', function(req, res) {
res.render('send', { csrfToken: req.csrfToken() })
})

Inside the view (depending on your template language; handlebars-style is demonstrated here), set the csrfToken value as
the value of a hidden input field named _csrf :

<form action="/process" method="POST">


<input type="hidden" name="_csrf" value="{{csrfToken}}">

Favorite color: <input type="text" name="favoriteColor">


<button type="submit">Submit</button>
</form>

Custom error handling

var express = require('express')


var csrf = require('csurf')

var app = express()


app.use(csrf())

// error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)

// handle CSRF token errors here


res.status(403)
res.send('session has expired or form tampered with')
})

License
MIT
connect-timeout
npm v1.4.0 downloads 712k/month build passing coverage 100% tips $10/week

Times out the request in ms , defaulting to 5000 .

Install

$ npm install connect-timeout

API
NOTE This module is not recommend as a "top-level" middleware (i.e. app.use(timeout('5s')) ) unless you take
precautions to halt your own middleware processing. See as top-level middleware for how to use as a top-level middleware.

timeout(time, options)

Returns middleware that times out in time milliseconds. time can also be a string accepted by the ms module. On
timeout, req will emit "timeout" .

options

respond - If true , the timeout error is passed to next() so that you may customize the response behavior. This error

has a .timeout property as well as .status == 503 . This defaults to true .

req.clearTimeout()

Clears the timeout on the request.

req.timedout

true if timeout fired; false otherwise.

Examples

as top-level middleware

Because of the way middleware processing works, this once this module passes the request to the next middleware (which
it has to do in order for you to do work), it can no longer stop the flow, so you must take care to check if the request has
timedout before you continue to act on the request.

var express = require('express');


var timeout = require('connect-timeout');

// example of using this top-level; note the use of haltOnTimedout


// after every middleware; it will stop the request flow on a timeout
var app = express();
app.use(timeout('5s'));
app.use(bodyParser());
app.use(haltOnTimedout);
app.use(cookieParser());
app.use(haltOnTimedout);
// Add your routes here, etc.

function haltOnTimedout(req, res, next){


if (!req.timedout) next();
}

app.listen(3000);

express 3.x

var express = require('express');


var bodyParser = require('body-parser');
var timeout = require('connect-timeout');

var app = express();


app.post('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function(req, res, next){
savePost(req.body, function(err, id){
if (err) return next(err);
if (req.timedout) return;
res.send('saved as id ' + id);
});
});

function haltOnTimedout(req, res, next){


if (!req.timedout) next();
}

function savePost(post, cb){


setTimeout(function(){
cb(null, ((Math.random()* 40000) >>> 0));
}, (Math.random()* 7000) >>> 0));
}

app.listen(3000);

connect

var bodyParser = require('body-parser');


var connect = require('connect');
var timeout = require('connect-timeout');

var app = require('connect');


app.use('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function(req, res, next){
savePost(req.body, function(err, id){
if (err) return next(err);
if (req.timedout) return;
res.send('saved as id ' + id);
});
});

function haltOnTimedout(req, res, next){


if (!req.timedout) next();
}

function savePost(post, cb){


setTimeout(function(){
cb(null, ((Math.random()* 40000) >>> 0));
}, (Math.random()* 7000) >>> 0));
}

app.listen(3000);

License
MIT
method-override
npm v2.3.0 downloads 819k/month build passing coverage 100% tips $10/week

Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it.

Install

$ npm install method-override

API
NOTE It is very important that this module is used before any module that needs to know the method of the request (for
example, it must be used prior to the csurf module).

methodOverride(getter, options)

Create a new middleware function to override the req.method property with a new value. This value will be pulled from the
provided getter .

getter - The getter to use to look up the overridden request method for the request. (default: X-HTTP-Method-Override )

options.methods - The allowed methods the original request must be in to check for a method override value. (default:

['POST'] )

If the found method is supported by node.js core, then req.method will be set to this value, as if it has originally been that
value. The previous req.method value will be stored in req.originalMethod .

getter

This is the method of getting the override value from the request. If a function is provided, the req is passed as the first
argument, the `res as the second argument and the method is expected to be returned. If a string is provided, the string is
used to look up the method with the following rules:

If the string starts with X- , then it is treated as the name of a header and that header is used for the method override.
If the request contains the same header multiple times, the first occurrence is used.
All other strings are treated as a key in the URL query string.

options.methods

This allows the specification of what methods(s) the request MUST be in in order to check for the method override value.
This defaults to only POST methods, which is the only method the override should arrive in. More methods may be
specified here, but it may introduce security issues and cause weird behavior when requests travel through caches. This
value is an array of methods in upper-case. null can be specified to allow all methods.

Examples

override using a header

To use a header to override the method, specify the header name as a string argument to the methodOverride function. To
then make the call, send a POST request to a URL with the overridden method as the value of that header. This method of
using a header would typically be used in conjunction with XMLHttpRequest on implementations that do not support the
method you are trying to use.

var connect = require('connect')


var methodOverride = require('method-override')

// override with the X-HTTP-Method-Override header in the request


app.use(methodOverride('X-HTTP-Method-Override'))

Example call with header override using XMLHttpRequest :

var xhr = new XMLHttpRequest()


xhr.onload = onload
xhr.open('post', '/resource', true)
xhr.setRequestHeader('X-HTTP-Method-Override', 'DELETE')
xhr.send()

function onload() {
alert('got response: ' + this.responseText)
}

override using a query value

To use a query string value to override the method, specify the query string key as a string argument to the methodOverride
function. To then make the call, send a POST request to a URL with the overridden method as the value of that query string
key. This method of using a query value would typically be used in conjunction with plain HTML <form> elements when
trying to support legacy browsers but still use newer methods.

var connect = require('connect')


var methodOverride = require('method-override')

// override with POST having ?_method=DELETE


app.use(methodOverride('_method'))

Example call with query override using HTML <form> :

<form method="POST" action="/resource?_method=DELETE">


<button type="submit">Delete resource</button>
</form>

multiple format support

var connect = require('connect')


var methodOverride = require('method-override')

// override with different headers; last one takes precedence


app.use(methodOverride('X-HTTP-Method')) // Microsoft
app.use(methodOverride('X-HTTP-Method-Override')) // Google/GData
app.use(methodOverride('X-Method-Override')) // IBM

custom logic

You can implement any kind of custom logic with a function for the getter . The following implements the logic for looking
in req.body that was in method-override@1 :

var bodyParser = require('body-parser')


var connect = require('connect')
var methodOverride = require('method-override')
// NOTE: when using req.body, you must fully parse the request body
// before you call methodOverride() in your middleware stack,
// otherwise req.body will not be populated.
app.use(bodyParser.urlencoded())
app.use(methodOverride(function(req, res){
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
var method = req.body._method
delete req.body._method
return method
}
}))

Example call with query override using HTML <form> :

<!-- enctype must be set to the type you will parse before methodOverride() -->
<form method="POST" action="/resource" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete resource</button>
</form>

License
MIT
Multer build passing npm package 0.1.6

Multer is a node.js middleware for handling multipart/form-data .

It is written on top of busboy for maximum efficiency.

API

Installation
$ npm install multer

Usage

var express = require('express')


var multer = require('multer')

var app = express()


app.use(multer({ dest: './uploads/'}))

You can access the fields and files in the request object:

console.log(req.body)
console.log(req.files)

IMPORTANT: Multer will not process any form which is not multipart/form-data .

Multer file object


A multer file object is a JSON object with the following properties.

1. fieldname - Field name specified in the form


2. originalname - Name of the file on the user's computer
3. name - Renamed file name
4. encoding - Encoding type of the file
5. mimetype - Mime type of the file
6. path - Location of the uploaded file
7. extension - Extension of the file
8. size - Size of the file in bytes
9. truncated - If the file was truncated due to size limitation
10. buffer - Raw data (is null unless the inMemory option is true)

Options
Multer accepts an options object, the most basic of which is the dest property, which tells Multer where to upload the files.
In case you omit the options object, the file will be renamed and uploaded to the temporary directory of the system. If the
inMemory option is true, no data is written to disk but data is kept in a buffer accessible in the file object.

By the default, Multer will rename the files so as to avoid name conflicts. The renaming function can be customized
according to your needs.

The following are the options that can be passed to Multer.


dest

limits

includeEmptyFields

inMemory

rename(fieldname, filename)

onFileUploadStart(file)

onFileUploadData(file, data)

onFileUploadComplete(file)

onParseStart()

onParseEnd(req, next)

onError()

onFileSizeLimit(file)

onFilesLimit()

onFieldsLimit()

onPartsLimit()

Apart from these, Multer also supports more advanced busboy options like highWaterMark , fileHwm , and defCharset .

In an average web app, only dest and rename might be required, and configured as shown in the example.

app.use(multer({
dest: './uploads/',
rename: function (fieldname, filename) {
return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
}
}))

The details of the properties of the options object is explained in the following sections.

dest

The destination directory for the uploaded files.

dest: './uploads/'

limits

An object specifying the size limits of the following optional properties. This object is passed to busboy directly, and the
details of properties can be found on busboy's page

fieldNameSize - integer - Max field name size (Default: 100 bytes)

fieldSize - integer - Max field value size (Default: 1MB)

fields - integer - Max number of non-file fields (Default: Infinity)

fileSize - integer - For multipart forms, the max file size (in bytes) (Default: Infinity)

files - integer - For multipart forms, the max number of file fields (Default: Infinity)

parts - integer - For multipart forms, the max number of parts (fields + files) (Default: Infinity)

headerPairs - integer - For multipart forms, the max number of header key=>value pairs to parse Default: 2000 (same

as node's http).

limits: {
fieldNameSize: 100,
files: 2,
fields: 5
}

Specifying the limits can help protect your site against denial of service (DoS) attacks.
includeEmptyFields

A Boolean value to specify whether empty submitted values should be processed and applied to req.body ; defaults to
false ;

includeEmptyFields: true

inMemory

If this Boolean value is true, the file.buffer property holds the data in-memory that Multer would have written to disk. The
dest option is still populated and the path property contains the proposed path to save the file. Defaults to false .

inMemory: true

rename(fieldname, filename)

Function to rename the uploaded files. Whatever the function returns will become the new name of the uploaded file
(extension is not included). The fieldname and filename of the file will be available in this function, use them if you need
to.

rename: function (fieldname, filename) {


return fieldname + filename + Date.now()
}

onFileUploadStart(file)

Event handler triggered when a file starts to be uploaded. A file object with the following properties are available to this
function: fieldname , originalname , name , encoding , mimetype , path , extension .

onFileUploadStart: function (file) {


console.log(file.fieldname + ' is starting ...')
}

You can even stop a file from being uploaded - just return false from the event handler. The file won't be processed or
reach the file system.

onFileUploadStart: function (file) {


if (file.originalname == 'virus.exe') return false;
}

onFileUploadData(file, data)

Event handler triggered when a chunk of buffer is received. A buffer object along with a file object is available to the
function.

onFileUploadData: function (file, data) {


console.log(data.length + ' of ' + file.fieldname + ' arrived')
}

onFileUploadComplete(file)
Event handler trigger when a file is completely uploaded. A file object is available to the function.

onFileUploadComplete: function (file) {


console.log(file.fieldname + ' uploaded to ' + file.path)
}

onParseStart()

Event handler triggered when the form parsing starts.

onParseStart: function () {
console.log('Form parsing started at: ', new Date())
}

onParseEnd(req, next)

Event handler triggered when the form parsing completes. The request object and the next objects are are passed to the
function.

onParseEnd: function (req, next) {


console.log('Form parsing completed at: ', new Date());

// usage example: custom body parse


req.body = require('qs').parse(req.body);

// call the next middleware


next();
}

Note: If you have created a onParseEnd event listener, you must manually call the next() function, else the request will be
left hanging.

onError()

Event handler for any errors encountering while processing the form. The error object and the next object is available to
the function. If you are handling errors yourself, make sure to terminate the request or call the next() function, else the
request will be left hanging.

onError: function (error, next) {


console.log(error)
next(error)
}

onFileSizeLimit()

Event handler triggered when a file size exceeds the specification in the limit object. No more files will be parsed after
the limit is reached.

onFileSizeLimit: function (file) {


console.log('Failed: ', file.originalname)
fs.unlink('./' + file.path) // delete the partially written file
}

onFilesLimit()

Event handler triggered when the number of files exceed the specification in the limit object. No more files will be parsed
after the limit is reached.

onFilesLimit: function () {
console.log('Crossed file limit!')
}

onFieldsLimit()

Event handler triggered when the number of fields exceed the specification in the limit object. No more fields will be
parsed after the limit is reached.

onFieldsLimit: function () {
console.log('Crossed fields limit!')
}

onPartsLimit()

Event handler triggered when the number of parts exceed the specification in the limit object. No more files or fields will
be parsed after the limit is reached.

onPartsLimit: function () {
console.log('Crossed parts limit!')
}

MIT Licensed
body-parser
npm v1.10.0 downloads 1M/month build passing coverage 100% tips $10/week

Node.js body parsing middleware.

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be
interested in the following modules:

busboy and connect-busboy


multiparty and connect-multiparty
formidable
multer

Other body parsers you might be interested in:

body
co-body

Installation

$ npm install body-parser

API

var bodyParser = require('body-parser')

bodyParser.json(options)

Returns middleware that only parses json . This parser accepts any Unicode encoding of the body and supports automatic
inflation of gzip and deflate encodings.

The options are:

strict - only parse objects and arrays. (default: true )

inflate - if deflated bodies will be inflated. (default: true )

limit - maximum request body size. (default: <100kb> )

reviver - passed to JSON.parse()

type - request content-type to parse (default: json )

verify - function to verify body content

The type argument is passed directly to the type-is library. This can be an extension name (like json ), a mime type (like
application/json ), or a mime time with a wildcard (like */json ).

The verify argument, if supplied, is called as verify(req, res, buf, encoding) , where buf is a Buffer of the raw
request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.

The reviver argument is passed directly to JSON.parse as the second argument. You can find more information on this
argument in the MDN documentation about JSON.parse.

bodyParser.raw(options)
Returns middleware that parses all bodies as a Buffer . This parser supports automatic inflation of gzip and deflate
encodings.

The options are:

inflate - if deflated bodies will be inflated. (default: true )

limit - maximum request body size. (default: <100kb> )

type - request content-type to parse (default: application/octet-stream )

verify - function to verify body content

The type argument is passed directly to the type-is library. This can be an extension name (like bin ), a mime type (like
application/octet-stream ), or a mime time with a wildcard (like application/* ).

The verify argument, if supplied, is called as verify(req, res, buf, encoding) , where buf is a Buffer of the raw
request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.

bodyParser.text(options)

Returns middleware that parses all bodies as a string. This parser supports automatic inflation of gzip and deflate
encodings.

The options are:

defaultCharset - the default charset to parse as, if not specified in content-type. (default: utf-8 )

inflate - if deflated bodies will be inflated. (default: true )

limit - maximum request body size. (default: <100kb> )

type - request content-type to parse (default: text/plain )

verify - function to verify body content

The type argument is passed directly to the type-is library. This can be an extension name (like txt ), a mime type (like
text/plain ), or a mime time with a wildcard (like text/* ).

The verify argument, if supplied, is called as verify(req, res, buf, encoding) , where buf is a Buffer of the raw
request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.

bodyParser.urlencoded(options)

Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and
supports automatic inflation of gzip and deflate encodings.

The options are:

extended - parse extended syntax with the qs module. (default: true , but using the default has been deprecated.

Please research into the difference between qs and querystring and choose the appropriate setting)
inflate - if deflated bodies will be inflated. (default: true )

limit - maximum request body size. (default: <100kb> )

parameterLimit - maximum number of parameters. (default: 1000 )

type - request content-type to parse (default: urlencoded )

verify - function to verify body content

The extended argument allows to choose between parsing the urlencoded data with the querystring library (when false )
or the qs library (when true ). The "extended" syntax allows for rich objects and arrays to be encoded into the urlencoded
format, allowing for a JSON-like experience with urlencoded. For more information, please see the qs library.

The parameterLimit argument controls the maximum number of parameters that are allowed in the urlencoded data. If a
request contains more parameters than this value, a 413 will be returned to the client.

The type argument is passed directly to the type-is library. This can be an extension name (like urlencoded ), a mime type
(like application/x-www-form-urlencoded ), or a mime time with a wildcard (like */x-www-form-urlencoded ).

The verify argument, if supplied, is called as verify(req, res, buf, encoding) , where buf is a Buffer of the raw
request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.

req.body

A new body object containing the parsed data is populated on the request object after the middleware.

Examples

express/connect top-level generic

This example demonstrates adding a generic JSON and urlencoded parser as a top-level middleware, which will parse the
bodies of all incoming requests. This is the simplest setup.

var express = require('express')


var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {


res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})

express route-specific

This example demonstrates adding body parsers specifically to the routes that need them. In general, this is the most
recommend way to use body-parser with express.

var express = require('express')


var bodyParser = require('body-parser')

var app = express()

// create application/json parser


var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser


var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies


app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})

// POST /api/users gets JSON bodies


app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
// create user in req.body
})

change content-type for parsers

All the parsers accept a type option which allows you to change the Content-Type that the middleware will parse.
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

// parse some custom thing into a Buffer


app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// parse an HTML body into a string


app.use(bodyParser.text({ type: 'text/html' }))

License
MIT

Vous aimerez peut-être aussi