Expressjs Middleware
Expressjs Middleware
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.
Regards,
Mario Martínez (ewiggin)
Fast, unopinionated, minimalist web framework for node.
app.listen(3000)
Installation
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
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
Install dependencies:
$ npm install
$ 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:
$ node examples/content-negotiation
Tests
To run the test suite, first install the dependancies, then run npm test :
$ npm install
$ npm test
People
License
MIT
Middleware
errorhandler
npm v1.3.0 downloads 799k/month build passing coverage 100% tips $10/week
Install
API
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:
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).
Sometimes you may want to output the errors to a different location than STDERR during development, like a system
notification, for example.
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
API
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
session(options)
Session data is not saved in the cookie itself, just the session ID.
Options
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:
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:
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:
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()
req.session.destroy(function(err) {
// cannot access session here
})
Session.reload()
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
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.
.get(sid, callback)
.destroy(sid, callback)
.length(callback)
.clear(callback)
License
MIT
morgan
npm v1.5.0 downloads 978k/month build passing coverage 100% tips $10/week
Named after Dexter, a show you should not watch until completion.
API
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
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) .
stream
Predefined Formats
combined
:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
common
Standard Apache common log output.
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.
short
tiny
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:
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:
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 )
:http-version
:method
: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
:req[header]
:res[header]
:response-time
The time between the request coming into morgan and when the response headers are written, in milliseconds.
:status
:url
The URL of the request. This will use req.originalUrl if exists, otherwise req.url .
:user-agent
Examples
express/connect
Simple app that will log all request in the Apache combined format to STDOUT
app.use(morgan('combined'))
Simple app that will log all request in the Apache combined format to STDOUT
// 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!')
})
})
Simple app that will log all request in the Apache combined format to the file "access.log"
Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.
app.use(assignId)
app.use(morgan(':id :method :url :response-time'))
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
API
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.
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
app.listen(8080)
MIT Licensed
serve-favicon
npm v2.2.0 downloads 787k/month build passing coverage 100% tips $10/week
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
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
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
app.listen(3000);
connect
var connect = require('connect');
var favicon = require('serve-favicon');
app.listen(3000);
This middleware can be used anywhere, even outside express/connect. It takes req , res , and callback .
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
API
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
session(options)
Session data is not saved in the cookie itself, just the session ID.
Options
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:
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:
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:
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()
req.session.destroy(function(err) {
// cannot access session here
})
Session.reload()
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
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.
.get(sid, callback)
.destroy(sid, callback)
.length(callback)
.clear(callback)
License
MIT
response-time
npm v2.2.0 downloads 703k/month build passing coverage 100% tips $10/week
Installation
API
responseTime(options)
Options
digits
The fixed number of digits to include in the output, which is always in milliseconds, defaults to 3 (ex: 2.300ms ).
header
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
app.use(responseTime())
// create "middleware"
var _responseTime = responseTime()
// 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
API
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").
'ignore' Pretend like the dotfile does not exist and call next() .
etag
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'] .
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
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:
Examples
// Create server
var server = http.createServer(function(req, res){
var done = finalhandler(req, res)
serve(req, res, done)
})
// Listen
server.listen(3000)
// Create server
var server = http.createServer(function(req, res){
var done = finalhandler(req, res)
serve(req, res, done)
})
// Listen
server.listen(3000)
License
MIT
serve-index
npm v1.5.3 downloads 826k/month build passing coverage 100% tips $10/week
Install
API
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
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
icons
stylesheet
template
view
Examples
// 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)
License
MIT. The Silk icons are created by/copyright of FAMFAMFAM.
csurf
npm v1.6.3 downloads 701k/month build passing coverage 100%
session
cookie-session
Install
API
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
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
req.csrfToken()
Example
The following is an example of some server-side code that protects all non-GET/HEAD/OPTIONS routes with a CSRF
token.
// error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
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 :
// error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
License
MIT
connect-timeout
npm v1.4.0 downloads 712k/month build passing coverage 100% tips $10/week
Install
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
req.clearTimeout()
req.timedout
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.
app.listen(3000);
express 3.x
app.listen(3000);
connect
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
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
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.
function onload() {
alert('got response: ' + this.responseText)
}
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.
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 :
<!-- 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
API
Installation
$ npm install multer
Usage
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 .
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.
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
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
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.
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 .
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.
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.
onFileUploadComplete(file)
Event handler trigger when a file is completely uploaded. A file object is available to the function.
onParseStart()
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.
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.
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.
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
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:
body
co-body
Installation
API
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 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 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.
defaultCharset - the default charset to parse as, if not specified in content-type. (default: utf-8 )
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.
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 )
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
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.
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
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.
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' }))
License
MIT