Express json body

Express json body DEFAULT

Getting the Request Body in Express

Oct 22, 2019

Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4.16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.

JSON Request Body

Express has a built-in function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The middleware adds a property to the Express request . To access the parsed request body, use as shown below.

Common Gotchas

If the JSON body is malformed, Express will error out with an HTTP 400. This error also triggers error handling middleware.

It is important to note that, by default, the middleware ignores any request whose header isn't something that Express recognizes as JSON. If is silently ignoring your request, make sure you check the header.

URL-Encoded Form Body Parser

Express has an officially supported module body-parser that includes a parser for URL-encoded request bodies, like the ones submitted by HTML forms.

Files

Neither Express nor body-parser supports file uploads out of the box. However, you can use the Formidable module on npm to handle file uploads. You can learn how on our tutorial on file uploads with Express.


Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

More Express Tutorials

Sours: https://masteringjs.io/tutorials/express/body

Introduction

In this brief article we'll be going over how to extract information from a POST body in Express.js. The HTTP protocol provides a number of ways to pass information from a client to a server, with POST bodies being the most flexible and most commonly used method to send data via HTTP.

Another way, which is typically used for different use-cases, is to convey information using query strings or URL parameters. For more info, check out how to get query strings and parameters in Express.js.

For this article I assume you have some experience with Node.js and creating simple Express.js servers.

Sending POST Data in HTTP

Data can be sent via an HTTP POST call for many reasons, with some of the most common being via an HTML or an API request. The data can take on a few different forms, with the most common being:

  • : Data in this encoding is formatted like a query string you'd see in a URL, with key-value paris being separated by characters. For example: . This is the default encoding.
  • : This encoding is typically used for sending files. In short, each key-value is sent in the same request, but different "parts", which are separated by "boundaries" and include more meta-data.
  • : This data is just sent as unstructured plain text, and typically is not used.

A raw HTTP POST request with the encoding might look something like this:

Before we can get started accessing POST data right away, we need to properly configure our Express app. This configuration needs to be done since not all web app servers need body parsing, and what body parsing is enabled depends on your application.

To set this up, we'll be using the body-parser package, which can handle many forms of data. This package is a middleware that intercepts the raw body and parses it in to a form that your application code can easily use.

Notice how we call before defining our route. The order here matters. This will ensure that the will run before our route, which ensures that our route can then access the parsed HTTP POST body.

To test this, we'll first start the Express app and then use the utility in a different console window:

Here you can see that the query string data was parsed in to a JavaScript object that we can easily access.

Another important thing to note is our use of the option when calling . Using the option tells to use the library to parse the URL-encoded data. This allows for things like objects and arrays to be encoded into the URL-encoded format.

And while is one of the most commonly used parsers that provides, you can also use the following:

  • : Parses JSON-formatted text for bodies with a of .
  • : Parses HTTP body in to a for specified custom s, although the default accepted is .
  • : Parses HTTP bodies with a of , which returns it as a plain string.

Each of these parsers also supports automatic inflation of data encoded with gzip or deflate, so compression can still be transparently used without any extra work by your application code.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The great thing about the middleware model and how this package parses data is that you're not stuck to using just one parser. You can enable one or more parsers for your app to ensure that all data types are processed properly:

So now if we were to send an HTTP POST request with JSON as the body, it will be parsed in to a regular JSON object in the property:

Conclusion

The most common way to send diverse and large amounts of data via HTTP is to use the POST method. Before we can easily access this data on the server side in Express, we need to use some middleware, like the package, to parse the data in to a format that we can easily access. Once the data from the raw HTTP request is parsed, it can then be accessed via the property of the object.

In this article we explained a bit about the various content types/encodings, how to use the package and its various options, and how to access the parsed data. If you see any issues or have suggestions, feel free to leave a comment below.

Sours: https://stackabuse.com/get-http-post-body-in-express-js/
  1. Infectious disease flashcards
  2. I3 3240 socket
  3. Owl brewery boston
  4. Wheel refinishing indianapolis
  5. Tahoe headlight

body-parser

Note: This page was generated from the body-parser README.

NPM VersionNPM DownloadsBuild StatusTest Coverage

Node.js body parsing middleware.

Parse incoming request bodies in a middleware before your handlers, available under the property.

Note As ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, may fail in multiple ways, for example the property may not be there or may not be a string, and may not be a function and instead a string or other user input.

Learn about the anatomy of an HTTP transaction in Node.js.

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:

This module provides the following parsers:

Other body parsers you might be interested in:

Installation

API

The object exposes various factories to create middlewares. All middlewares will populate the property with the parsed body when the request header matches the option, or an empty object () if there was no body to parse, the was not matched, or an error occurred.

The various errors returned by this module are described in the errors section.

bodyParser.json([options])

Returns middleware that only parses and only looks at requests where the header matches the option. This parser accepts any Unicode encoding of the body and supports automatic inflation of and encodings.

A new object containing the parsed data is populated on the object after the middleware (i.e. ).

Options

The function takes an optional object that may contain any of the following keys:

inflate

When set to , then deflated (compressed) bodies will be inflated; when , deflated bodies are rejected. Defaults to .

limit

Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to .

reviver

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

strict

When set to , will only accept arrays and objects; when will accept anything accepts. Defaults to .

type

The option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, option is passed directly to the type-is library and this can be an extension name (like ), a mime type (like ), or a mime type with a wildcard (like or ). If a function, the option is called as and the request is parsed if it returns a truthy value. Defaults to .

verify

The option, if supplied, is called as , where is a of the raw request body and is the encoding of the request. The parsing can be aborted by throwing an error.

bodyParser.raw([options])

Returns middleware that parses all bodies as a and only looks at requests where the header matches the option. This parser supports automatic inflation of and encodings.

A new object containing the parsed data is populated on the object after the middleware (i.e. ). This will be a object of the body.

Options

The function takes an optional object that may contain any of the following keys:

inflate

When set to , then deflated (compressed) bodies will be inflated; when , deflated bodies are rejected. Defaults to .

limit

Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to .

type

The option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, option is passed directly to the type-is library and this can be an extension name (like ), a mime type (like ), or a mime type with a wildcard (like or ). If a function, the option is called as and the request is parsed if it returns a truthy value. Defaults to .

verify

The option, if supplied, is called as , where is a of the raw request body and 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 and only looks at requests where the header matches the option. This parser supports automatic inflation of and encodings.

A new string containing the parsed data is populated on the object after the middleware (i.e. ). This will be a string of the body.

Options

The function takes an optional object that may contain any of the following keys:

defaultCharset

Specify the default character set for the text content if the charset is not specified in the header of the request. Defaults to .

inflate

When set to , then deflated (compressed) bodies will be inflated; when , deflated bodies are rejected. Defaults to .

limit

Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to .

type

The option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, option is passed directly to the type-is library and this can be an extension name (like ), a mime type (like ), or a mime type with a wildcard (like or ). If a function, the option is called as and the request is parsed if it returns a truthy value. Defaults to .

verify

The option, if supplied, is called as , where is a of the raw request body and is the encoding of the request. The parsing can be aborted by throwing an error.

bodyParser.urlencoded([options])

Returns middleware that only parses bodies and only looks at requests where the header matches the option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of and encodings.

A new object containing the parsed data is populated on the object after the middleware (i.e. ). This object will contain key-value pairs, where the value can be a string or array (when is ), or any type (when is ).

Options

The function takes an optional object that may contain any of the following keys:

extended

The option allows to choose between parsing the URL-encoded data with the library (when ) or the library (when ). The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.

Defaults to , but using the default has been deprecated. Please research into the difference between and and choose the appropriate setting.

inflate

When set to , then deflated (compressed) bodies will be inflated; when , deflated bodies are rejected. Defaults to .

limit

Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. Defaults to .

parameterLimit

The option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, a 413 will be returned to the client. Defaults to .

type

The option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, option is passed directly to the type-is library and this can be an extension name (like ), a mime type (like ), or a mime type with a wildcard (like ). If a function, the option is called as and the request is parsed if it returns a truthy value. Defaults to .

verify

The option, if supplied, is called as , where is a of the raw request body and is the encoding of the request. The parsing can be aborted by throwing an error.

Errors

The middlewares provided by this module create errors using the module. The errors will typically have a / property that contains the suggested HTTP response code, an property to determine if the property should be displayed to the client, a property to determine the type of error without matching against the , and a property containing the read body, if available.

The following are the common errors created, though any error can come through for various reasons.

content encoding unsupported

This error will occur when the request had a header that contained an encoding but the “inflation” option was set to . The property is set to , the property is set to , and the property will be set to the encoding that is unsupported.

entity parse failed

This error will occur when the request contained an entity that could not be parsed by the middleware. The property is set to , the property is set to , and the property is set to the entity value that failed parsing.

entity verify failed

This error will occur when the request contained an entity that could not be failed verification by the defined option. The property is set to , the property is set to , and the property is set to the entity value that failed verification.

request aborted

This error will occur when the request is aborted by the client before reading the body has finished. The property will be set to the number of bytes received before the request was aborted and the property is set to the number of expected bytes. The property is set to and property is set to .

request entity too large

This error will occur when the request body’s size is larger than the “limit” option. The property will be set to the byte limit and the property will be set to the request body’s length. The property is set to and the property is set to .

request size did not match content length

This error will occur when the request’s length did not match the length from the header. This typically occurs when the request is malformed, typically when the header was calculated based on characters instead of bytes. The property is set to and the property is set to .

stream encoding should not be set

This error will occur when something called the method prior to this middleware. This module operates directly on bytes only and you cannot call when using this module. The property is set to and the property is set to .

too many parameters

This error will occur when the content of the request exceeds the configured for the parser. The property is set to and the property is set to .

unsupported charset “BOGUS”

This error will occur when the request had a charset parameter in the header, but the module does not support it OR the parser does not support it. The charset is contained in the message as well as in the property. The property is set to , the property is set to , and the property is set to the charset that is unsupported.

unsupported content encoding “bogus”

This error will occur when the request had a header that contained an unsupported encoding. The encoding is contained in the message as well as in the property. The property is set to , the property is set to , and the property is set to the encoding that is unsupported.

Examples

Express/Connect top-level generic

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

Express route-specific

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

Change accepted type for parsers

All the parsers accept a option which allows you to change the that the middleware will parse.

License

MIT

Sours: https://expressjs.com/en/resources/middleware/body-parser.html
Learn Express JS by building a Project - BodyParser

Parsing JSON bodies

Drop-in example

Here is an example app that reflects the request POST body in the response:

You can see it running at https://olrn6x3n19.sse.codesandbox.io/, test it using:

It will output:

Which is exactly what we sent in the property of the curl request.

Extended configuration options

You can pass options into it like so (all the values are the default values for these options):

The full API docs for are at expressjs.com/en/api.html#express.json.

A run-through of the options follows.

controls whether or not to handle compressed/deflated request bodies. When it’s set to false, compressed/deflated bodies will get rejected.

controls the maximum body size. It can be either a number of bytes or a string which is compatible with the bytes library.

is about locking JSON.parse down to just objects and arrays. If true, only -ed objects and arrays will be allowed, if false, anything that JSON.parse accepts will be parsed.

controls which content-type the middleware will attempt to parse. The value for this option can be a string, an array of strings, or a function. Content-type wildcards are supported to some extent since string(s) are passed to the type-is library.

is an optional function with signature. is a Buffer containing the raw request body. can be used to abort parsing by throwing an error.

Parsing URL encoded form bodies

In the same way we used we can use .

Drop-in example

We pass to avoid a warning.

You can see it running at https://6njqzmyw4k.sse.codesandbox.io/, test it using the form on the page.

Extended configuration options

You can pass options into like so (all the values are the default values for these options):

The full API docs for are at expressjs.com/en/api.html#express.urlencoded.

A run-through of the options follows.

pretty much a toggle between the (when ) and (when ) libraries. allows for rich objects and arrays to be encoded, does not. Keep this as for simple forms (all key-value pairs) and when you’re sending arrays/maps of values.

controls whether or not to handle compressed/deflated request bodies. When it’s set to false, compressed/deflated bodies will get rejected.

controls the maximum body size. It can be either a number of bytes or a string which is compatible with the bytes library.

controls the maximum number of fields that we’ll attempt to parse from the url encoded form body.

controls which content-type the middleware will attempt to parse. The value for this option can be a string, an array of strings, or a function. Content-type wildcards are supported to some extent since string(s) are passed to the type-is library.

is an optional function with signature. is a Buffer containing the raw request body. can be used to abort parsing by throwing an error.

More about body-parser and other body-parsing libraries

This means we don’t need to install body-parser to load up most of our bodies. Express’ built-in JSON and URL encoded form body parsing covers the majority of use cases. What we might need a library for is multipart bodies, there are alternative libraries to handle that use-case (usually for file upload).

There are still some very specific cases where body-parser might still be necessary (see the docs at github.com/expressjs/body-parser):

Mahir Uysal

Sours: https://codewithhugo.com/parse-express-json-form-body/

Json body express

4.x API

express()

Creates an Express application. The function is a top-level function exported by the module.

Methods

express.json([options])

This middleware is available in Express v4.16.0 onwards.

This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

Returns middleware that only parses JSON and only looks at requests where the header matches the option. This parser accepts any Unicode encoding of the body and supports automatic inflation of and encodings.

A new object containing the parsed data is populated on the object after the middleware (i.e. ), or an empty object () if there was no body to parse, the was not matched, or an error occurred.

As ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, may fail in multiple ways, for example may not be there or may not be a string, and may not be a function and instead a string or other user-input.

The following table describes the properties of the optional object.

PropertyDescriptionTypeDefault
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.Boolean
Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing.Mixed
The option is passed directly to as the second argument. You can find more information on this argument in the MDN documentation about JSON.parse.Function
Enables or disables only accepting arrays and objects; when disabled will accept anything accepts.Boolean
This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, option is passed directly to the type-is library and this can be an extension name (like ), a mime type (like ), or a mime type with a wildcard (like or ). If a function, the option is called as and the request is parsed if it returns a truthy value.Mixed
This option, if supplied, is called as , where is a of the raw request body and is the encoding of the request. The parsing can be aborted by throwing an error.Function

express.raw([options])

This middleware is available in Express v4.17.0 onwards.

This is a built-in middleware function in Express. It parses incoming request payloads into a and is based on body-parser.

Returns middleware that parses all bodies as a and only looks at requests where the header matches the option. This parser accepts any Unicode encoding of the body and supports automatic inflation of and encodings.

A new containing the parsed data is populated on the object after the middleware (i.e. ), or an empty object () if there was no body to parse, the was not matched, or an error occurred.

As ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, may fail in multiple ways, for example stacking multiple parsers may be from a different parser. Testing that is a before calling buffer methods is recommended.

The following table describes the properties of the optional object.

PropertyDescriptionTypeDefault
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.Boolean
Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing.Mixed
This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, option is passed directly to the type-is library and this can be an extension name (like ), a mime type (like ), or a mime type with a wildcard (like or ). If a function, the option is called as and the request is parsed if it returns a truthy value.Mixed
This option, if supplied, is called as , where is a of the raw request body and is the encoding of the request. The parsing can be aborted by throwing an error.Function

express.Router([options])

Creates a new router object.

The optional parameter specifies the behavior of the router.

You can add middleware and HTTP method routes (such as , , , and so on) to just like an application.

For more information, see Router.

express.static(root, [options])

This is a built-in middleware function in Express. It serves static files and is based on serve-static.

NOTE: For best results, use a reverse proxy cache to improve performance of serving static assets.

The argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining with the provided directory. When a file is not found, instead of sending a 404 response, it instead calls to move on to the next middleware, allowing for stacking and fall-backs.

The following table describes the properties of the object. See also the example below.

PropertyDescriptionTypeDefault
Determines how dotfiles (files or directories that begin with a dot “.”) are treated.

See dotfiles below.
String“ignore”
Enable or disable etag generation

NOTE: always sends weak ETags.
Boolean
Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: .Mixed
Let client errors fall-through as unhandled requests, otherwise forward a client error.

See fallthrough below.
Boolean
Enable or disable the directive in the response header. If enabled, the option should also be specified to enable caching. The directive will prevent supported clients from making conditional requests during the life of the option to check if the file has changed.Boolean
Sends the specified directory index file. Set to to disable directory indexing.Mixed“index.html”
Set the header to the last modified date of the file on the OS.Boolean
Set the max-age property of the Cache-Control header in milliseconds or a string in ms format.Number0
Redirect to trailing “/” when the pathname is a directory.Boolean
Function for setting HTTP headers to serve with the file.

See setHeaders below.
Function

For more information, see Serving static files in Express. and Using middleware - Built-in middleware.

dotfiles

Possible values for this option are:

  • “allow” - No special treatment for dotfiles.
  • “deny” - Deny a request for a dotfile, respond with , then call .
  • “ignore” - Act as if the dotfile does not exist, respond with , then call .

NOTE: With the default value, it will not ignore files in a directory that begins with a dot.

fallthrough

When this option is , client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke .

Set this option to so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.

Use if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.

The signature of the function is:

Arguments:

  • , the response object.
  • , the file path that is being sent.
  • , the object of the file that is being sent.

Example of express.static

Here is an example of using the middleware function with an elaborate options object:

express.text([options])

This middleware is available in Express v4.17.0 onwards.

This is a built-in middleware function in Express. It parses incoming request payloads into a string and is based on body-parser.

Returns middleware that parses all bodies as a string and only looks at requests where the header matches the option. This parser accepts any Unicode encoding of the body and supports automatic inflation of and encodings.

A new string containing the parsed data is populated on the object after the middleware (i.e. ), or an empty object () if there was no body to parse, the was not matched, or an error occurred.

As ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, may fail in multiple ways, for example stacking multiple parsers may be from a different parser. Testing that is a string before calling string methods is recommended.

The following table describes the properties of the optional object.

PropertyDescriptionTypeDefault
Specify the default character set for the text content if the charset is not specified in the header of the request.String
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.Boolean
Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing.Mixed
This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, option is passed directly to the type-is library and this can be an extension name (like ), a mime type (like ), or a mime type with a wildcard (like or ). If a function, the option is called as and the request is parsed if it returns a truthy value.Mixed
This option, if supplied, is called as , where is a of the raw request body and is the encoding of the request. The parsing can be aborted by throwing an error.Function

express.urlencoded([options])

This middleware is available in Express v4.16.0 onwards.

This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.

Returns middleware that only parses urlencoded bodies and only looks at requests where the header matches the option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of and encodings.

A new object containing the parsed data is populated on the object after the middleware (i.e. ), or an empty object () if there was no body to parse, the was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when is ), or any type (when is ).

As ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, may fail in multiple ways, for example may not be there or may not be a string, and may not be a function and instead a string or other user-input.

The following table describes the properties of the optional object.

PropertyDescriptionTypeDefault
This option allows to choose between parsing the URL-encoded data with the library (when ) or the library (when ). The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.Boolean
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.Boolean
Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing.Mixed
This option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, an error will be raised.Number
This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, option is passed directly to the type-is library and this can be an extension name (like ), a mime type (like ), or a mime type with a wildcard (like ). If a function, the option is called as and the request is parsed if it returns a truthy value.Mixed
This option, if supplied, is called as , where is a of the raw request body and is the encoding of the request. The parsing can be aborted by throwing an error.Function

Application

The object conventionally denotes the Express application. Create it by calling the top-level function exported by the Express module:

The object has methods for

It also has settings (properties) that affect how the application behaves; for more information, see Application settings.

Properties

app.locals

The object has properties that are local variables within the application.

Once set, the value of properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via (see req.app)

app.mountpath

The property contains one or more path patterns on which a sub-app was mounted.

A sub-app is an instance of that may be used for handling the request to a route.

It is similar to the baseUrl property of the object, except returns the matched URL path, instead of the matched patterns.

If a sub-app is mounted on multiple path patterns, returns the list of patterns it is mounted on, as shown in the following example.

Events

app.on('mount', callback(parent))

The event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.

NOTE

Sub-apps will:

  • Not inherit the value of settings that have a default value. You must set the value in the sub-app.
  • Inherit the value of settings with no default value.

For details, see Application settings.

Methods

app.all(path, callback [, callback ...])

This method is like the standard app.METHOD() methods, except it matches all HTTP verbs.

Arguments

Argument Description Default
The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
For examples, see Path examples.
'/' (root path)
Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

Examples

The following callback is executed for requests to whether using GET, POST, PUT, DELETE, or any other HTTP request method:

The method is useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end-points: can perform a task, then call to continue matching subsequent routes.

Or the equivalent:

Another example is white-listed “global” functionality. The example is similar to the ones above, but it only restricts paths that start with “/api”:

app.delete(path, callback [, callback ...])

Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the routing guide.

Arguments

Argument Description Default
The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
For examples, see Path examples.
'/' (root path)
Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

Example

app.disable(name)

Sets the Boolean setting to , where is one of the properties from the app settings table. Calling for a Boolean property is the same as calling .

For example:

app.disabled(name)

Returns if the Boolean setting is disabled (), where is one of the properties from the app settings table.

app.enable(name)

Sets the Boolean setting to , where is one of the properties from the app settings table. Calling for a Boolean property is the same as calling .

app.enabled(name)

Returns if the setting is enabled (), where is one of the properties from the app settings table.

app.engine(ext, callback)

Registers the given template engine as .

By default, Express will the engine based on the file extension. For example, if you try to render a “foo.pug” file, Express invokes the following internally, and caches the on subsequent calls to increase performance.

Use this method for engines that do not provide out of the box, or if you wish to “map” a different extension to the template engine.

For example, to map the EJS template engine to “.html” files:

In this case, EJS provides a method with the same signature that Express expects: , though note that it aliases this method as internally so if you’re using “.ejs” extensions you don’t need to do anything.

Some template engines do not follow this convention. The consolidate.js library maps Node template engines to follow this convention, so they work seamlessly with Express.

app.get(name)

Returns the value of app setting, where is one of the strings in the app settings table. For example:

app.get(path, callback [, callback ...])

Routes HTTP GET requests to the specified path with the specified callback functions.

Arguments

Argument Description Default
The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
For examples, see Path examples.
'/' (root path)
Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

For more information, see the routing guide.

Example

app.listen(path, [callback])

Starts a UNIX socket and listens for connections on the given path. This method is identical to Node’s http.Server.listen().

app.listen([port[, host[, backlog]]][, callback])

Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).

The returned by is in fact a JavaScript , designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

The method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.METHOD(path, callback [, callback ...])

Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are , , , and so on. See Routing methods below for the complete list.

Arguments

Argument Description Default
The path for which the middleware function is invoked; can be any of:
  • A string representing a path.
  • A path pattern.
  • A regular expression pattern to match paths.
  • An array of combinations of any of the above.
For examples, see Path examples.
'/' (root path)
Callback functions; can be:
  • A middleware function.
  • A series of middleware functions (separated by commas).
  • An array of middleware functions.
  • A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For examples, see Middleware callback function examples.

None

Routing methods

Express supports the following routing methods corresponding to the HTTP methods of the same names:

        The API documentation has explicit entries only for the most popular HTTP methods , , , and . However, the other methods listed above work in exactly the same way.

        To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, .

        The function is automatically called for the HTTP method in addition to the method if was not called for the path before .

        The method, , is not derived from any HTTP method and loads middleware at the specified path for all HTTP request methods. For more information, see app.all.

        For more information on routing, see the routing guide.

        app.param([name], callback)

        Add callback triggers to route parameters, where is the name of the parameter or an array of them, and is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.

        If is an array, the trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to inside the callback will call the callback for the next declared parameter. For the last parameter, a call to will call the next middleware in place for the route currently being processed, just like it would if were just a string.

        For example, when is present in a route path, you may map user loading logic to automatically provide to the route, or perform validations on the parameter input.

        Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on will be triggered only by route parameters defined on routes.

        All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.

        On , the following is printed:

        On , the following is printed:

        The following section describes , which is deprecated as of v4.11.0.

        The behavior of the method can be altered entirely by passing only a function to . This function is a custom implementation of how should behave - it accepts two parameters and must return a middleware.

        The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.

        The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.

        In this example, the signature is modified to . Instead of accepting a name and a callback, will now accept a name and a number.

        In this example, the signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.

        The ‘’ character can’t be used to capture a character in your capturing regexp. For example you can’t use to capture , use or instead (as in .

        Examples:

        app.path()

        Returns the canonical path of the app, a string.

        The behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use req.baseUrl to get the canonical path of the app.

        app.post(path, callback [, callback ...])

        Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the routing guide.

        Arguments

        Argument Description Default
        The path for which the middleware function is invoked; can be any of:
        • A string representing a path.
        • A path pattern.
        • A regular expression pattern to match paths.
        • An array of combinations of any of the above.
        For examples, see Path examples.
        '/' (root path)
        Callback functions; can be:
        • A middleware function.
        • A series of middleware functions (separated by commas).
        • An array of middleware functions.
        • A combination of all of the above.

        You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

        Since router and app implement the middleware interface, you can use them as you would any other middleware function.

        For examples, see Middleware callback function examples.

        None

        Example

        app.put(path, callback [, callback ...])

        Routes HTTP PUT requests to the specified path with the specified callback functions.

        Arguments

        Argument Description Default
        The path for which the middleware function is invoked; can be any of:
        • A string representing a path.
        • A path pattern.
        • A regular expression pattern to match paths.
        • An array of combinations of any of the above.
        For examples, see Path examples.
        '/' (root path)
        Callback functions; can be:
        • A middleware function.
        • A series of middleware functions (separated by commas).
        • An array of middleware functions.
        • A combination of all of the above.

        You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

        Since router and app implement the middleware interface, you can use them as you would any other middleware function.

        For examples, see Middleware callback function examples.

        None

        Example

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

        Returns the rendered HTML of a view via the function. It accepts an optional parameter that is an object containing local variables for the view. It is like res.render(), except it cannot send the rendered view to the client on its own.

        Think of as a utility function for generating rendered view strings. Internally uses to render views.

        The local variable is reserved for enabling view cache. Set it to , if you want to cache view during development; view caching is enabled in production by default.

        app.route(path)

        Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use to avoid duplicate route names (and thus typo errors).

        app.set(name, value)

        Assigns setting to . You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the app settings table.

        Calling for a Boolean property is the same as calling . Similarly, calling for a Boolean property is the same as calling .

        Retrieve the value of a setting with .

        Application Settings

        The following table lists application settings.

        Note that sub-apps will:

        • Not inherit the value of settings that have a default value. You must set the value in the sub-app.
        • Inherit the value of settings with no default value; these are explicitly noted in the table below.

        Exceptions: Sub-apps will inherit the value of even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of in production (when is “production”).

        app.use([path,] callback [, callback...])

        Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches .

        Arguments

        Argument Description Default
        The path for which the middleware function is invoked; can be any of:
        • A string representing a path.
        • A path pattern.
        • A regular expression pattern to match paths.
        • An array of combinations of any of the above.
        For examples, see Path examples.
        '/' (root path)
        Callback functions; can be:
        • A middleware function.
        • A series of middleware functions (separated by commas).
        • An array of middleware functions.
        • A combination of all of the above.

        You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

        Since router and app implement the middleware interface, you can use them as you would any other middleware function.

        For examples, see Middleware callback function examples.

        None

        Description

        A route will match any path that follows its path immediately with a “”. For example: will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.

        Since defaults to “/”, middleware mounted without a path will be executed for every request to the app.
        For example, this middleware function will be executed for every request to the app:

        NOTE

        Sub-apps will:

        • Not inherit the value of settings that have a default value. You must set the value in the sub-app.
        • Inherit the value of settings with no default value.

        For details, see Application settings.

        Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

        Error-handling middleware

        Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the object, you must specify it to maintain the signature. Otherwise, the object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: Error handling.

        Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature ):

        Path examples

        The following table provides some simple examples of valid values for mounting middleware.

        Middleware callback function examples

        The following table provides some simple examples of middleware functions that can be used as the argument to , , and . Even though the examples are for , they are also valid for , , and .

        UsageExample
        Single Middleware

        You can define and mount a middleware function locally.

        A router is valid middleware.

        An Express app is valid middleware.

        Series of Middleware

        You can specify more than one middleware function at the same mount path.

        Array

        Use an array to group middleware logically.

        Combination

        You can combine all the above ways of mounting middleware.

        Following are some examples of using the express.static middleware in an Express app.

        Serve static content for the app from the “public” directory in the application directory:

        Mount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:

        Disable logging for static content requests by loading the logger middleware after the static middleware:

        Serve static files from multiple directories, but give precedence to “./public” over the others:

        Request

        The object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as (and the HTTP response is ) but its actual name is determined by the parameters to the callback function in which you’re working.

        For example:

        But you could just as well have:

        The object is an enhanced version of Node’s own request object and supports all built-in fields and methods.

        Properties

        req.app

        This property holds a reference to the instance of the Express application that is using the middleware.

        If you follow the pattern in which you create a module that just exports a middleware function and it in your main file, then the middleware can access the Express instance via

        For example:

        req.baseUrl

        The URL path on which a router instance was mounted.

        The property is similar to the mountpath property of the object, except returns the matched path pattern(s).

        For example:

        Even if you use a path pattern or a set of path patterns to load the router, the property returns the matched string, not the pattern(s). In the following example, the router is loaded on two path patterns.

        When a request is made to , is “/greet”. When a request is made to , is “/hello”.

        req.body

        Contains key-value pairs of data submitted in the request body. By default, it is , and is populated when you use body-parsing middleware such as or .

        The following example shows how to use body-parsing middleware to populate .

        req.cookies

        When using cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to .

        If the cookie has been signed, you have to use req.signedCookies.

        For more information, issues, or concerns, see cookie-parser.

        req.fresh

        When the response is still “fresh” in the client’s cache is returned, otherwise is returned to indicate that the client cache is now stale and the full response should be sent.

        When a client sends the request header to indicate an end-to-end reload request, this module will return to make handling these requests transparent.

        Further details for how cache validation works can be found in the HTTP/1.1 Caching Specification.

        req.hostname

        Contains the hostname derived from the HTTP header.

        When the setting does not evaluate to , this property will instead get the value from the header field. This header can be set by the client or by the proxy.

        If there is more than one header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.

        Prior to Express v4.17.0, the could not contain multiple values or be present more than once.

        req.ip

        Contains the remote IP address of the request.

        When the setting does not evaluate to , the value of this property is derived from the left-most entry in the header. This header can be set by the client or by the proxy.

        req.ips

        When the setting does not evaluate to , this property contains an array of IP addresses specified in the request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.

        For example, if is , would be , where is the furthest downstream.

        req.method

        Contains a string corresponding to the HTTP method of the request: , , , and so on.

        req.originalUrl

        is not a native Express property, it is inherited from Node’s http module.

        This property is much like ; however, it retains the original request URL, allowing you to rewrite freely for internal routing purposes. For example, the “mounting” feature of app.use() will rewrite to strip the mount point.

        is available both in middleware and router objects, and is a combination of and . Consider following example:

        req.params

        This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route , then the “name” property is available as . This object defaults to .

        When you use a regular expression for the route definition, capture groups are provided in the array using , where is the nth capture group. This rule is applied to unnamed wild card matches with string routes such as :

        If you need to make changes to a key in , use the app.param handler. Changes are applicable only to parameters already defined in the route path.

        Any changes made to the object in a middleware or route handler will be reset.

        NOTE: Express automatically decodes the values in (using ).

        req.path

        Contains the path part of the request URL.

        When called from a middleware, the mount point is not included in . See app.use() for more details.

        req.protocol

        Contains the request protocol string: either or (for TLS requests) .

        When the setting does not evaluate to , this property will use the value of the header field if present. This header can be set by the client or by the proxy.

        req.query

        This property is an object containing a property for each query string parameter in the route. When query parser is set to disabled, it is an empty object , otherwise it is the result of the configured query parser.

        As ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, may fail in multiple ways, for example may not be there or may not be a string, and may not be a function and instead a string or other user-input.

        req.route

        Contains the currently-matched route, a string. For example:

        Example output from the previous snippet:

        req.secure

        A Boolean property that is true if a TLS connection is established. Equivalent to:

        req.signedCookies

        When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on values (which are easy to spoof). Note that signing a cookie does not make it “hidden” or encrypted; but simply prevents tampering (because the secret used to sign is private).

        If no signed cookies are sent, the property defaults to .

        For more information, issues, or concerns, see cookie-parser.

        req.stale

        Indicates whether the request is “stale,” and is the opposite of . For more information, see req.fresh.

        req.subdomains

        An array of subdomains in the domain name of the request.

        The application property , which defaults to 2, is used for determining the beginning of the subdomain segments. To change this behavior, change its value using app.set.

        req.xhr

        A Boolean property that is if the request’s header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery.

        Methods

        req.accepts(types)

        Checks if the specified content types are acceptable, based on the request’s HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns (in which case, the application should respond with ).

        The value may be a single MIME type string (such as “application/json”), an extension name such as “json”, a comma-delimited list, or an array. For a list or array, the method returns the best match (if any).

        For more information, or if you have issues or concerns, see accepts.

        req.acceptsCharsets(charset [, ...])

        Returns the first accepted charset of the specified character sets, based on the request’s HTTP header field. If none of the specified charsets is accepted, returns .

        For more information, or if you have issues or concerns, see accepts.

        req.acceptsEncodings(encoding [, ...])

        Returns the first accepted encoding of the specified encodings, based on the request’s HTTP header field. If none of the specified encodings is accepted, returns .

        For more information, or if you have issues or concerns, see accepts.

        req.acceptsLanguages(lang [, ...])

        Returns the first accepted language of the specified languages, based on the request’s HTTP header field. If none of the specified languages is accepted, returns .

        For more information, or if you have issues or concerns, see accepts.

        req.get(field)

        Returns the specified HTTP request header field (case-insensitive match). The and fields are interchangeable.

        Aliased as .

        req.is(type)

        Returns the matching content type if the incoming request’s “Content-Type” HTTP header field matches the MIME type specified by the parameter. If the request has no body, returns . Returns otherwise.

        For more information, or if you have issues or concerns, see type-is.

        req.param(name [, defaultValue])

        Deprecated. Use either , or , as applicable.

        Returns the value of param when present.

        Lookup is performed in the following order:

          Optionally, you can specify to set a default value if the parameter is not found in any of the request objects.

          Direct access to , , and should be favoured for clarity - unless you truly accept input from each object.

          Body-parsing middleware must be loaded for to work predictably. Refer req.body for details.

          req.range(size[, options])

          header parser.

          The parameter is the maximum size of the resource.

          The parameter is an object that can have the following properties.

          PropertyTypeDescription
          BooleanSpecify if overlapping & adjacent ranges should be combined, defaults to . When , ranges will be combined and returned as if they were specified that way in the header.

          An array of ranges will be returned or negative numbers indicating an error parsing.

          • signals a malformed header string
          • signals an unsatisfiable range

          Response

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

          In this documentation and by convention, the object is always referred to as (and the HTTP request is ) but its actual name is determined by the parameters to the callback function in which you’re working.

          For example:

          But you could just as well have:

          The object is an enhanced version of Node’s own response object and supports all built-in fields and methods.

          Properties

          res.app

          This property holds a reference to the instance of the Express application that is using the middleware.

          is identical to the req.app property in the request object.

          Boolean property that indicates if the app sent HTTP headers for the response.

          res.locals

          An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

          This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

          Methods

          res.append(field [, value])

          is supported by Express v4.11.0+

          Appends the specified to the HTTP response header . If the header is not already set, it creates the header with the specified value. The parameter can be a string or an array.

          Note: calling after will reset the previously-set header value.

          res.attachment([filename])

          Sets the HTTP response header field to “attachment”. If a is given, then it sets the Content-Type based on the extension name via , and sets the “filename=” parameter.

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

          Sets cookie to . The parameter may be a string or object converted to JSON.

          The parameter is an object that can have the following properties.

          PropertyTypeDescription
          StringDomain name for the cookie. Defaults to the domain name of the app.
          FunctionA synchronous function used for cookie value encoding. Defaults to .
          DateExpiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie.
          BooleanFlags the cookie to be accessible only by the web server.
          NumberConvenient option for setting the expiry time relative to the current time in milliseconds.
          StringPath for the cookie. Defaults to “/”.
          BooleanMarks the cookie to be used with HTTPS only.
          BooleanIndicates if the cookie should be signed.
          Boolean or StringValue of the “SameSite” Set-Cookie attribute. More information at https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1.

          All does is set the HTTP header with the options provided. Any option not specified defaults to the value stated in RFC 6265.

          For example:

          You can set multiple cookies in a single response by calling multiple times, for example:

          The option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions.

          Example use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values.

          The option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the second example above.

          You can pass an object as the parameter; it is then serialized as JSON and parsed by middleware.

          When using cookie-parser middleware, this method also supports signed cookies. Simply include the option set to . Then will use the secret passed to to sign the value.

          Later you may access this value through the req.signedCookie object.

          res.clearCookie(name [, options])

          Clears the cookie specified by . For details about the object, see res.cookie().

          Web browsers and other compliant clients will only clear the cookie if the given is identical to those given to res.cookie(), excluding and .

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

          The optional argument is supported by Express v4.16.0 onwards.

          Transfers the file at as an “attachment”. Typically, browsers will prompt the user for download. By default, the header “filename=” parameter is (this typically appears in the browser dialog). Override this default with the parameter.

          When an error occurs or transfer is complete, the method calls the optional callback function . This method uses res.sendFile() to transfer the file.

          The optional argument passes through to the underlying res.sendFile() call, and takes the exact same parameters.

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

          Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.

          Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().

          res.format(object)

          Performs content-negotiation on the HTTP header on the request object, when present. It uses req.accepts() to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 “Not Acceptable”, or invokes the callback.

          The response header is set when a callback is selected. However, you may alter this within the callback using methods such as or .

          The following example would respond with when the header field is set to “application/json” or “*/json” (however if it is “*/*”, then the response will be “hey”).

          In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:

          res.get(field)

          Returns the HTTP response header specified by . The match is case-insensitive.

          res.json([body])

          Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

          The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.

          res.jsonp([body])

          Sends a JSON response with JSONP support. This method is identical to , except that it opts-in to JSONP callback support.

          By default, the JSONP callback name is simply . Override this with the jsonp callback name setting.

          The following are some examples of JSONP responses using the same code:

          res.links(links)

          Joins the provided as properties of the parameter to populate the response’s HTTP header field.

          For example, the following call:

          Yields the following results:

          res.location(path)

          Sets the response HTTP header to the specified parameter.

          A value of “back” has a special meaning, it refers to the URL specified in the header of the request. If the header was not specified, it refers to “/”.

          After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the header, without any validation.

          Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the header; and redirect the user accordingly.

          res.redirect([status,] path)

          Redirects to the URL derived from the specified , with specified , a positive integer that corresponds to an HTTP status code . If not specified, defaults to “302 “Found”.

          Redirects can be a fully-qualified URL for redirecting to a different site:

          Redirects can be relative to the root of the host name. For example, if the application is on , the following would redirect to the URL :

          Redirects can be relative to the current URL. For example, from (notice the trailing slash), the following would redirect to the URL .

          Redirecting to from (no trailing slash), will redirect to .

          If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.

          Path-relative redirects are also possible. If you were on , the following would redirect to :

          A redirection redirects the request back to the referer, defaulting to when the referer is missing.

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

          Renders a and sends the rendered HTML string to the client. Optional parameters:

          • , an object whose properties define local variables for the view.
          • , a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes internally.

          The argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the setting. If the path does not contain a file extension, then the setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via ) and render it using the loaded module’s function.

          For more information, see Using template engines with Express.

          NOTE: The argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user.

          The local variable enables view caching. Set it to , to cache the view during development; view caching is enabled in production by default.

          res.send([body])

          Sends the HTTP response.

          The parameter can be a object, a , an object, , or an . For example:

          This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.

          When the parameter is a object, the method sets the response header field to “application/octet-stream”, unless previously defined as shown below:

          When the parameter is a , the method sets the to “text/html”:

          When the parameter is an or , Express responds with the JSON representation:

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

          is supported by Express v4.8.0 onwards.

          Transfers the file at the given . Sets the response HTTP header field based on the filename’s extension. Unless the option is set in the options object, must be an absolute path to the file.

          This API provides access to data on the running file system. Ensure that either (a) the way in which the argument was constructed into an absolute path is secure if it contains user input or (b) set the option to the absolute path of a directory to contain access within.

          When the option is provided, the argument is allowed to be a relative path, including containing . Express will validate that the relative path provided as will resolve within the given option.

          The following table provides details on the parameter.

          The method invokes the callback function when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.

          Here is an example of using with all its arguments.

          The following example illustrates using to provide fine-grained support for serving files:

          For more information, or if you have issues or concerns, see send.

          res.sendStatus(statusCode)

          Sets the response HTTP status code to and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.

          Some versions of Node.js will throw when is set to an invalid HTTP status code (outside of the range to ). Consult the HTTP server documentation for the Node.js version being used.

          More about HTTP Status Codes

          res.set(field [, value])

          Sets the response’s HTTP header to . To set multiple fields at once, pass an object as the parameter.

          Aliased as .

          res.status(code)

          Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.

          res.type(type)

          Sets the HTTP header to the MIME type as determined by the specified . If contains the “/” character, then it sets the to the exact value of , otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the method.

          res.vary(field)

          Adds the field to the response header, if it is not there already.

          Router

          A object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.

          A router behaves like middleware itself, so you can use it as an argument to app.use() or as the argument to another router’s use() method.

          The top-level object has a Router() method that creates a new object.

          Once you’ve created a router object, you can add middleware and HTTP method routes (such as , , , and so on) to it just like an application. For example:

          You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.

          Methods

          router.all(path, [callback, ...] callback)

          This method is just like the methods, except that it matches all HTTP methods (verbs).

          This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you placed the following route at the top of all other route definitions, it would require that all routes from that point on would require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end points; can perform a task, then call to continue matching subsequent routes.

          Or the equivalent:

          Another example of this is white-listed “global” functionality. Here the example is much like before, but it only restricts paths prefixed with “/api”:

          router.METHOD(path, [callback, ...] callback)

          The methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are , , , and so on.

          The function is automatically called for the HTTP method in addition to the method if was not called for the path before .

          You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched.

          The following snippet illustrates the most simple route definition possible. Express translates the path strings to regular expressions, used internally to match incoming requests. Query strings are not considered when performing these matches, for example “GET /” would match the following route, as would “GET /?name=tobi”.

          You can also use regular expressions—useful if you have very specific constraints, for example the following would match “GET /commits/71dbb9c” as well as “GET /commits/71dbb9c..4c084f9”.

          router.param(name, callback)

          Adds callback triggers to route parameters, where is the name of the parameter and is the callback function. Although is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below).

          The parameters of the callback function are:

          • , the request object.
          • , the response object.
          • , indicating the next middleware function.
          • The value of the parameter.
          • The name of the parameter.

          Unlike , does not accept an array of route parameters.

          For example, when is present in a route path, you may map user loading logic to automatically provide to the route, or perform validations on the parameter input.

          Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on will be triggered only by route parameters defined on routes.

          A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.

          On , the following is printed:

          The following section describes , which is deprecated as of v4.11.0.

          The behavior of the method can be altered entirely by passing only a function to . This function is a custom implementation of how should behave - it accepts two parameters and must return a middleware.

          The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.

          The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.

          In this example, the signature is modified to . Instead of accepting a name and a callback, will now accept a name and a number.

          In this example, the signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.

          router.route(path)

          Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use to avoid duplicate route naming and thus typing errors.

          Building on the example above, the following code shows how to use to specify various HTTP method handlers.

          This approach re-uses the single path and adds handlers for various HTTP methods.

          NOTE: When you use , middleware ordering is based on when the route is created, not when method handlers are added to the route. For this purpose, you can consider method handlers to belong to the route to which they were added.

          router.use([path], [function, ...] function)

          Uses the specified middleware function or functions, with optional mount path , that defaults to “/”.

          This method is similar to app.use(). A simple example and use case is described below. See app.use() for more information.

          Middleware is like a plumbing pipe: requests start at the first middleware function defined and work their way “down” the middleware stack processing for each path they match.

          The “mount” path is stripped and is not visible to the middleware function. The main effect of this feature is that a mounted middleware function may operate without code changes regardless of its “prefix” pathname.

          The order in which you define middleware with is very important. They are invoked sequentially, thus the order defines middleware precedence. For example, usually a logger is the very first middleware you would use, so that every request gets logged.

          Now suppose you wanted to ignore logging requests for static files, but to continue logging routes and middleware defined after . You would simply move the call to to the top, before adding the logger middleware:

          Another example is serving files from multiple directories, giving precedence to “./public” over the others:

          The method also supports named parameters so that your mount points for other routers can benefit from preloading using named parameters.

          NOTE: Although these middleware functions are added via a particular router, when they run is defined by the path they are attached to (not the router). Therefore, middleware added via one router may run for other routers if its routes match. For example, this code shows two different routers mounted on the same path:

          Even though the authentication middleware was added via the it will run on the routes defined by the as well since both routers were mounted on . To avoid this behavior, use different paths for each router.

          Sours: http://expressjs.com/en/api.html
          Use body-parser to Parse POST Requests - Basic Node and Express - Free Code Camp

          Get HTTP request body data using Node.js

          Here is how you can extract the data that was sent as JSON in the request body.

          If you are using Express, that's quite simple: use the Node.js module.

          For example, to get the body of this request:

          JS

          const axios =require('axios')

          axios.post('https://whatever.com/todos',{

          todo:'Buy the milk'

          })

          This is the matching server-side code:

          JS

          const express =require('express')

          const app =express()

          app.use(

          express.urlencoded({

          extended:true

          })

          )

          app.use(express.json())

          app.post('/todos',(req, res)=>{

          console.log(req.body.todo)

          })

          If you're not using Express and you want to do this in vanilla Node.js, you need to do a bit more work, of course, as Express abstracts a lot of this for you.

          The key thing to understand is that when you initialize the HTTP server using , the callback is called when the server got all the HTTP headers, but not the request body.

          The object passed in the connection callback is a stream.

          So, we must listen for the body content to be processed, and it's processed in chunks.

          We first get the data by listening to the stream events, and when the data ends, the stream event is called, once:

          JS

          const server = http.createServer((req, res)=>{

          req.on('data',chunk=>{

          console.log(`Data chunk available: ${chunk}`)

          })

          req.on('end',()=>{

          })

          })

          So to access the data, assuming we expect to receive a string, we must concatenate the chunks into a string when listening to the stream , and when the stream , we parse the string to JSON:

          JS

          const server = http.createServer((req, res)=>{

          let data ='';

          req.on('data',chunk=>{

          data += chunk;

          })

          req.on('end',()=>{

          console.log(JSON.parse(data).todo);

          res.end();

          })

          })

          Starting from Node.js v10 a syntax is available for use. It simplifies the example above and makes it look more linear:

          JS

          const server = http.createServer(async(req, res)=>{

          const buffers =[];

          forawait(const chunk of req){

          buffers.push(chunk);

          }

          const data =Buffer.concat(buffers).toString();

          console.log(JSON.parse(data).todo);

          res.end();

          })

          Edit this page on GitHub

          Sours: https://nodejs.dev/learn/get-http-request-body-data-using-nodejs

          You will also like:

          Express.js express.json() Function

          The express.json() function is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

          Syntax:

          express.json( [options] )

          Parameters: The options parameter have various property like inflate, limit, type, etc.

          Return Value: It returns an Object.

          Installation of express module:



          1. You can visit the link to Install express module. You can install this package by using this command.npm install express
          2. After installing the express module, you can check your express version in command prompt using the command.npm version express
          3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js

          Example 1:Filename: index.js

           

           

           

          Steps to run the program:

          1. The project structure will look like this:
          2. Make sure you have installed express module using the following command:npm install express
          3. Run index.js file using below command:node index.js

            Output:

            Server listening on PORT 3000
          4. Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/json’ and body {“name”:”GeeksforGeeks”}, then you will see the following output on your console: Server listening on PORT 3000 GeeksforGeeks

          Example 2:Filename: index.js

           

           

          Run index.js file using below command:

          node index.js

          Now make a POST request to http://localhost:3000/ with header set to ‘content-type: application/json’ and body {“name”:”GeeksforGeeks”}, then you will see the following output on your console:

          Server listening on PORT 3000 TypeError: Cannot read property 'name' of undefined

          Reference:https://expressjs.com/en/4x/api.html#express.json




          Sours: https://www.geeksforgeeks.org/express-js-express-json-function/


          1 2 3