CINXE.COM

Express 4.x - API Reference

<!DOCTYPE html> <!--- Copyright (c) 2016 StrongLoop, IBM, and Express Contributors License: MIT --> <html lang="en"> <head> <title>Express 4.x - API Reference</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/png" href="/images/favicon.png" /> <script data-cfasync="false" src="/js/theme.js"></script> <link rel="stylesheet" href="/css/dark-theme.css?_=1733758360"> <link rel="stylesheet" href="/css/style.css?_=1733758360"> <link rel="stylesheet" href="/css/prism.css"> <link rel="stylesheet" href="/css/font-awesome.min.css"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&amp;amp;subset=latin,latin-ext"> <link rel="stylesheet" href="/css/en.css"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version."> <meta property="og:url" content="https://expressjs.com/en/4x/api.html"> <meta property="og:type" content="website" > <meta name="title" property="og:title" content="Express 4.x - API Reference"> <meta property="og:description" content="Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version."> <meta property="og:image" content="https://expressjs.com/images/og.png" > <meta name="twitter:card" content="summary_large_image"> <meta property="twitter:domain" content="expressjs.com"> <meta property="twitter:url" content="https://expressjs.com/en/4x/api.html"> <meta name="twitter:title" content="Express 4.x - API Reference"> <meta name="twitter:description" content="Access the API reference for Express.js 4.x, detailing all modules, methods, and properties for building web applications with this version."> <meta property="twitter:image" content="https://expressjs.com/images/og.png" > <script data-cfasync="false" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script data-cfasync="false" src="/js/ismobile.js"></script> <script data-cfasync="false" src="/js/app.js"></script> <script data-cfasync="false" defer src="/js/menu.js"></script> <script data-cfasync="false" src="/js/retina.js"></script> <script data-cfasync="false" src="/js/prism.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css" /> </head> <body> <section class="content"> <header> <div id="mobile-menu"> <div id="nav-button" class="fa fa-bars fa-2x button"></div> </div> <section id="logo"><a href="/" class="express">Express</a> </section> <div id="navbar"> <input id="q" placeholder="🔎 search"> <ul id="navmenu"> <li><a href="/" id="home-menu">Home</a></li> <li id="getting-started-menu" class="submenu"> <a href="/en/starter/installing.html">Getting started</a> <ul class="submenu-content"> <li> <a href="/en/starter/installing.html"> Installing </a> </li> <li> <a href="/en/starter/hello-world.html"> Hello world </a> </li> <li> <a href="/en/starter/generator.html"> Express generator </a> </li> <li> <a href="/en/starter/basic-routing.html"> Basic routing </a> </li> <li> <a href="/en/starter/static-files.html"> Static files </a> </li> <li> <a href="/en/starter/examples.html"> More examples </a> </li> <li> <a href="/en/starter/faq.html"> FAQ </a> </li> </ul> </li> <li id="guide-menu" class="submenu"> <a href="/en/guide/routing.html">Guide</a> <ul class="submenu-content"> <li><a href="/en/guide/routing.html">Routing</a> </li> <li><a href="/en/guide/writing-middleware.html">Writing middleware</a> </li> <li><a href="/en/guide/using-middleware.html">Using middleware</a> </li> <li><a href="/en/guide/overriding-express-api.html">Overriding the Express API</a> </li> <li><a href="/en/guide/using-template-engines.html">Using template engines</a> </li> <li><a href="/en/guide/error-handling.html">Error handling</a> </li> <li><a href="/en/guide/debugging.html">Debugging</a> </li> <li><a href="/en/guide/behind-proxies.html">Express behind proxies</a> </li> <li><a href="/en/guide/migrating-4.html">Moving to Express 4</a> </li> <li><a href="/en/guide/migrating-5.html">Moving to Express 5</a> </li> <li><a href="/en/guide/database-integration.html">Database integration</a> </li> </ul> </li> <li id="application-menu" class="submenu"> <a href="/en/5x/api.html" class="active">API reference</a> <ul class="submenu-content"> <li><a href="/en/5x/api.html">5.x</a> </li> <li><a href="/en/4x/api.html">4.x</a> </li> <li><a href="/en/3x/api.html">3.x (deprecated)</a> </li> <li><a href="/2x/">2.x (deprecated)</a> </li> </ul> </li> <li id="advanced-topics-menu" class="submenu"> <a href="/en/advanced/developing-template-engines.html">Advanced topics</a> <ul class="submenu-content"> <li><a href="/en/advanced/developing-template-engines.html">Building template engines</a> </li> <li><a href="/en/advanced/security-updates.html">Security updates</a> </li> <li><a href="/en/advanced/best-practice-security.html">Security best practices</a> </li> <li><a href="/en/advanced/best-practice-performance.html">Performance best practices</a> </li> <li><a href="/en/advanced/healthcheck-graceful-shutdown.html">Health checks & shutdown</a> </li> </ul> </li> <li id="resources-menu" class="submenu"> <a href="/en/resources/glossary.html">Resources</a> <ul class="submenu-content"> <li> <a href="/en/resources/community.html">Community</a> </li> <li> <a href="/en/resources/glossary.html">Glossary</a> </li> <li> <a href="/en/resources/middleware.html">Middleware</a> </li> <li> <a href="/en/resources/utils.html">Utility modules</a> </li> <li> <a href="/en/resources/contributing.html">Contributing to Express</a> </li> <li> <a href="/en/changelog/4x.html">Release Change Log</a> </li> </ul> </li> <li><a href="/en/support" id="support-menu">Support</a></li> <li id="blog-menu" class="submenu"> <a href="/2024/10/22/security-audit-milestone-achievement.html">Blog</a> <ul class="submenu-content"> <li> <a href="/2024/10/22/security-audit-milestone-achievement.html">Latest post</a> </li> <li> <a href="/en/blog/posts.html">All posts</a> </li> <li> <a href="/en/blog/write-post.html">Write a Post</a> </li> </ul> </li> </ul> </div> <div id="theme-icon-container" class="theme-toggle default-theme" title="toggle darkmode"> <i class="fa fa-moon-o fa-2x hidden-dark"></i> <span class="sun-icon hidden-light"></span> </div> </header> <ul id="menu"> <li id="express-api"><a href="#express">express()</a> <ul id="express-menu"> <li><em>Methods</em></li> <li id="express-json-middleware"><a href="#express.json">express.json()</a></li> <li id="express-raw"><a href="#express.raw">express.raw()</a></li> <li id="express-router"><a href="#express.router">express.Router()</a></li> <li id="express-static-middleware"><a href="#express.static">express.static()</a></li> <li id="express-text"><a href="#express.text">express.text()</a></li> <li id="express-urlencoded-middleware"><a href="#express.urlencoded">express.urlencoded()</a></li> </ul> </li> <li id="app-api"><a href="#app">Application</a> <ul id="app-menu"> <li><em>Properties</em> </li> <li><a href="#app.locals">app.locals</a> </li> <li><a href="#app.mountpath">app.mountpath</a> </li> <li><em>Events</em> </li> <li><a href="#app.onmount">mount</a> </li> <li><em>Methods</em> </li> <li><a href="#app.all">app.all()</a> </li> <li><a href="#app.delete.method">app.delete()</a> </li> <li><a href="#app.disable">app.disable()</a> </li> <li><a href="#app.disabled">app.disabled()</a> </li> <li><a href="#app.enable">app.enable()</a> </li> <li><a href="#app.enabled">app.enabled()</a> </li> <li><a href="#app.engine">app.engine()</a> </li> <li><a href="#app.get">app.get()</a> </li> <li><a href="#app.get.method">app.get()</a> </li> <li><a href="#app.listen">app.listen()</a> </li> <li><a href="#app.METHOD">app.METHOD()</a> </li> <li><a href="#app.param">app.param()</a> </li> <li><a href="#app.path">app.path()</a> </li> <li><a href="#app.post.method">app.post()</a> </li> <li><a href="#app.put.method">app.put()</a> </li> <li><a href="#app.render">app.render()</a> </li> <li><a href="#app.route">app.route()</a> </li> <li><a href="#app.set">app.set()</a> </li> <li><a href="#app.use">app.use()</a> </li> </ul> </li> <li id="req-api"><a href="#req">Request</a> <ul id="req-menu"> <li><em>Properties</em> </li> <li><a href="#req.app">req.app</a> </li> <li><a href="#req.baseUrl">req.baseUrl</a> </li> <li><a href="#req.body">req.body</a> </li> <li><a href="#req.cookies">req.cookies</a> </li> <li><a href="#req.fresh">req.fresh</a> </li> <li><a href="#req.hostname">req.hostname</a> </li> <li><a href="#req.ip">req.ip</a> </li> <li><a href="#req.ips">req.ips</a> </li> <li><a href="#req.method">req.method</a> </li> <li><a href="#req.originalUrl">req.originalUrl</a> </li> <li><a href="#req.params">req.params</a> </li> <li><a href="#req.path">req.path</a> </li> <li><a href="#req.protocol">req.protocol</a> </li> <li><a href="#req.query">req.query</a> </li> <li><a href="#req.res">req.res</a> </li> <li><a href="#req.route">req.route</a> </li> <li><a href="#req.secure">req.secure</a> </li> <li><a href="#req.signedCookies">req.signedCookies</a> </li> <li><a href="#req.stale">req.stale</a> </li> <li><a href="#req.subdomains">req.subdomains</a> </li> <li><a href="#req.xhr">req.xhr</a> </li> <li><em>Methods</em> </li> <li><a href="#req.accepts">req.accepts()</a> </li> <li><a href="#req.acceptsCharsets">req.acceptsCharsets()</a> </li> <li><a href="#req.acceptsEncodings">req.acceptsEncodings()</a> </li> <li><a href="#req.acceptsLanguages">req.acceptsLanguages()</a> </li> <li><a href="#req.get">req.get()</a> </li> <li><a href="#req.is">req.is()</a> </li> <li><a href="#req.param">req.param()</a> </li> <li><a href="#req.range">req.range()</a> </li> </ul> </li> <li id="res-api"><a href="#res">Response</a> <ul id="res-menu"> <li><em>Properties</em> </li> <li><a href="#res.app">res.app </a> </li> <li><a href="#res.headersSent">res.headersSent</a> </li> <li><a href="#res.locals">res.locals</a> </li> <li><em>Methods</em> </li> <li><a href="#res.append">res.append()</a> </li> <li><a href="#res.attachment">res.attachment()</a> </li> <li><a href="#res.cookie">res.cookie()</a> </li> <li><a href="#res.clearCookie">res.clearCookie()</a> </li> <li><a href="#res.download">res.download()</a> </li> <li><a href="#res.end">res.end()</a> </li> <li><a href="#res.format">res.format()</a> </li> <li><a href="#res.get">res.get()</a> </li> <li><a href="#res.json">res.json()</a> </li> <li><a href="#res.jsonp">res.jsonp()</a> </li> <li><a href="#res.links">res.links()</a> </li> <li><a href="#res.location">res.location()</a> </li> <li><a href="#res.redirect">res.redirect()</a> </li> <li><a href="#res.render">res.render()</a> </li> <li><a href="#res.send">res.send()</a> </li> <li><a href="#res.sendFile">res.sendFile()</a> </li> <li><a href="#res.sendStatus">res.sendStatus()</a> </li> <li><a href="#res.set">res.set()</a> </li> <li><a href="#res.status">res.status()</a> </li> <li><a href="#res.type">res.type()</a> </li> <li><a href="#res.vary">res.vary()</a> </li> </ul> </li> <li id="router-api"><a href="#router">Router</a> <ul id="router-menu"> <li><em>Methods</em> </li> <li><a href="#router.all">router.all()</a> </li> <li><a href="#router.METHOD">router.METHOD()</a> </li> <li><a href="#router.param">router.param()</a> </li> <li><a href="#router.route">router.route()</a> </li> <li><a href="#router.use">router.use()</a> </li> </ul> </li> </ul> <div id="overlay"></div> <div id="api-doc"> <h1>4.x API</h1> <div class="doc-box doc-info"> <p class="doc-info-title"><i class="fa fa-lg fa-info-circle"></i> Note</p> <p>Express 4.0 requires Node.js 0.10 or higher.</p> </div> <h2 id="express">express()</h2> <p>Creates an Express application. The <code>express()</code> function is a top-level function exported by the <code>express</code> module.</p> <pre><code class="language-js">var express = require('express') var app = express() </code></pre> <h3 id="express.methods">Methods</h3> <section> <h3 id="express.json" class="h2">express.json([options])</h3> <div class="doc-box doc-info"> <p>This middleware is available in Express v4.16.0 onwards.</p> </div> <p>This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on <a href="/resources/middleware/body-parser.html">body-parser</a>.</p> <p>Returns middleware that only parses JSON and only looks at requests where the <code>Content-Type</code> header matches the <code>type</code> option. This parser accepts any Unicode encoding of the body and supports automatic inflation of <code>gzip</code> and <code>deflate</code> encodings.</p> <p>A new <code>body</code> object containing the parsed data is populated on the <code>request</code> object after the middleware (i.e. <code>req.body</code>), or an empty object (<code>{}</code>) if there was no body to parse, the <code>Content-Type</code> was not matched, or an error occurred.</p> <div class="doc-box doc-warn"> <p>As <code>req.body</code>’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, <code>req.body.foo.toString()</code> may fail in multiple ways, for example <code>foo</code> may not be there or may not be a string, and <code>toString</code> may not be a function and instead a string or other user-input.</p> </div> <p>The following table describes the properties of the optional <code>options</code> object.</p> <table> <thead> <tr> <th>Property</th> <th>Description</th> <th>Type</th> <th>Default</th> </tr> </thead> <tbody> <tr> <td><code>inflate</code></td> <td>Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>limit</code></td> <td>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 <a href="https://www.npmjs.com/package/bytes">bytes</a> library for parsing.</td> <td>Mixed</td> <td><code>"100kb"</code></td> </tr> <tr> <td><code>reviver</code></td> <td>The <code>reviver</code> option is passed directly to <code>JSON.parse</code> as the second argument. You can find more information on this argument <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter">in the MDN documentation about JSON.parse</a>.</td> <td>Function</td> <td><code>null</code></td> </tr> <tr> <td><code>strict</code></td> <td>Enables or disables only accepting arrays and objects; when disabled will accept anything <code>JSON.parse</code> accepts.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>type</code></td> <td>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, <code>type</code> option is passed directly to the <a href="https://www.npmjs.org/package/type-is#readme">type-is</a> library and this can be an extension name (like <code>json</code>), a mime type (like <code>application/json</code>), or a mime type with a wildcard (like <code>*/*</code> or <code>*/json</code>). If a function, the <code>type</code> option is called as <code>fn(req)</code> and the request is parsed if it returns a truthy value.</td> <td>Mixed</td> <td><code>"application/json"</code></td> </tr> <tr> <td><code>verify</code></td> <td>This option, if supplied, is called as <code>verify(req, res, buf, encoding)</code>, where <code>buf</code> is a <code>Buffer</code> of the raw request body and <code>encoding</code> is the encoding of the request. The parsing can be aborted by throwing an error.</td> <td>Function</td> <td><code>undefined</code></td> </tr> </tbody> </table> </section> <section> <h3 id="express.raw" class="h2">express.raw([options])</h3> <div class="doc-box doc-info"> <p>This middleware is available in Express v4.17.0 onwards.</p> </div> <p>This is a built-in middleware function in Express. It parses incoming request payloads into a <code>Buffer</code> and is based on <a href="/resources/middleware/body-parser.html">body-parser</a>.</p> <p>Returns middleware that parses all bodies as a <code>Buffer</code> and only looks at requests where the <code>Content-Type</code> header matches the <code>type</code> option. This parser accepts any Unicode encoding of the body and supports automatic inflation of <code>gzip</code> and <code>deflate</code> encodings.</p> <p>A new <code>body</code> <code>Buffer</code> containing the parsed data is populated on the <code>request</code> object after the middleware (i.e. <code>req.body</code>), or an empty object (<code>{}</code>) if there was no body to parse, the <code>Content-Type</code> was not matched, or an error occurred.</p> <div class="doc-box doc-warn"> <p>As <code>req.body</code>’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, <code>req.body.toString()</code> may fail in multiple ways, for example stacking multiple parsers <code>req.body</code> may be from a different parser. Testing that <code>req.body</code> is a <code>Buffer</code> before calling buffer methods is recommended.</p> </div> <p>The following table describes the properties of the optional <code>options</code> object.</p> <table> <thead> <tr> <th>Property</th> <th>Description</th> <th>Type</th> <th>Default</th> </tr> </thead> <tbody> <tr> <td><code>inflate</code></td> <td>Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>limit</code></td> <td>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 <a href="https://www.npmjs.com/package/bytes">bytes</a> library for parsing.</td> <td>Mixed</td> <td><code>"100kb"</code></td> </tr> <tr> <td><code>type</code></td> <td>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, <code>type</code> option is passed directly to the <a href="https://www.npmjs.org/package/type-is#readme">type-is</a> library and this can be an extension name (like <code>bin</code>), a mime type (like <code>application/octet-stream</code>), or a mime type with a wildcard (like <code>*/*</code> or <code>application/*</code>). If a function, the <code>type</code> option is called as <code>fn(req)</code> and the request is parsed if it returns a truthy value.</td> <td>Mixed</td> <td><code>"application/octet-stream"</code></td> </tr> <tr> <td><code>verify</code></td> <td>This option, if supplied, is called as <code>verify(req, res, buf, encoding)</code>, where <code>buf</code> is a <code>Buffer</code> of the raw request body and <code>encoding</code> is the encoding of the request. The parsing can be aborted by throwing an error.</td> <td>Function</td> <td><code>undefined</code></td> </tr> </tbody> </table> </section> <section> <h3 id="express.router" class="h2">express.Router([options])</h3> <p>Creates a new <a href="#router">router</a> object.</p> <pre><code class="language-js">var router = express.Router([options]) </code></pre> <p>The optional <code>options</code> parameter specifies the behavior of the router.</p> <div class="table-scroller"> <table> <thead> <tr> <th>Property</th> <th>Description</th> <th>Default</th> <th>Availability</th> </tr> </thead> <tbody> <tr> <td><code>caseSensitive</code></td> <td>Enable case sensitivity.</td> <td>Disabled by default, treating “/Foo” and “/foo” as the same.</td> <td> </td> </tr> <tr> <td><code>mergeParams</code></td> <td>Preserve the <code>req.params</code> values from the parent router. If the parent and the child have conflicting param names, the child’s value take precedence.</td> <td><code>false</code></td> <td>4.5.0+</td> </tr> <tr> <td><code>strict</code></td> <td>Enable strict routing.</td> <td>Disabled by default, “/foo” and “/foo/” are treated the same by the router.</td> <td> </td> </tr> </tbody> </table> </div> <p>You can add middleware and HTTP method routes (such as <code>get</code>, <code>put</code>, <code>post</code>, and so on) to <code>router</code> just like an application.</p> <p>For more information, see <a href="#router">Router</a>.</p> </section> <section> <h3 id="express.static" class="h2">express.static(root, [options])</h3> <p>This is a built-in middleware function in Express. It serves static files and is based on <a href="/resources/middleware/serve-static.html">serve-static</a>.</p> <div class="doc-box doc-info"> <p class="doc-info-title"><i class="fa fa-lg fa-info-circle"></i> Note</p> <p>For best results, <a href="/en/advanced/best-practice-performance.html#use-a-reverse-proxy">use a reverse proxy</a> cache to improve performance of serving static assets.</p> </div> <p>The <code>root</code> argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining <code>req.url</code> with the provided <code>root</code> directory. When a file is not found, instead of sending a 404 response, it calls <code>next()</code> to move on to the next middleware, allowing for stacking and fall-backs.</p> <p>The following table describes the properties of the <code>options</code> object. See also the <a href="#example.of.express.static">example below</a>.</p> <table> <thead> <tr> <th>Property</th> <th>Description</th> <th>Type</th> <th>Default</th> </tr> </thead> <tbody> <tr> <td><code>dotfiles</code></td> <td>Determines how dotfiles (files or directories that begin with a dot “.”) are treated. <br /><br />See <a href="#dotfiles">dotfiles</a> below.</td> <td>String</td> <td><code>undefined</code></td> </tr> <tr> <td><code>etag</code></td> <td>Enable or disable etag generation <br /><br />NOTE: <code>express.static</code> always sends weak ETags.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>extensions</code></td> <td>Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: <code>['html', 'htm']</code>.</td> <td>Mixed</td> <td><code>false</code></td> </tr> <tr> <td><code>fallthrough</code></td> <td>Let client errors fall-through as unhandled requests, otherwise forward a client error. <br /><br />See <a href="#fallthrough">fallthrough</a> below.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>immutable</code></td> <td>Enable or disable the <code>immutable</code> directive in the <code>Cache-Control</code> response header. If enabled, the <code>maxAge</code> option should also be specified to enable caching. The <code>immutable</code> directive will prevent supported clients from making conditional requests during the life of the <code>maxAge</code> option to check if the file has changed.</td> <td>Boolean</td> <td><code>false</code></td> </tr> <tr> <td><code>index</code></td> <td>Sends the specified directory index file. Set to <code>false</code> to disable directory indexing.</td> <td>Mixed</td> <td>“index.html”</td> </tr> <tr> <td><code>lastModified</code></td> <td>Set the <code>Last-Modified</code> header to the last modified date of the file on the OS.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>maxAge</code></td> <td>Set the max-age property of the Cache-Control header in milliseconds or a string in <a href="https://www.npmjs.org/package/ms">ms format</a>.</td> <td>Number</td> <td>0</td> </tr> <tr> <td><code>redirect</code></td> <td>Redirect to trailing “/” when the pathname is a directory.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>setHeaders</code></td> <td>Function for setting HTTP headers to serve with the file. <br /><br />See <a href="#setHeaders">setHeaders</a> below.</td> <td>Function</td> <td> </td> </tr> </tbody> </table> <p>For more information, see <a href="/starter/static-files.html">Serving static files in Express</a>. and <a href="/en/guide/using-middleware.html#middleware.built-in">Using middleware - Built-in middleware</a>.</p> <h5 id="dotfiles">dotfiles</h5> <p>Possible values for this option are:</p> <ul> <li>“allow” - No special treatment for dotfiles.</li> <li>“deny” - Deny a request for a dotfile, respond with <code>403</code>, then call <code>next()</code>.</li> <li>“ignore” - Act as if the dotfile does not exist, respond with <code>404</code>, then call <code>next()</code>.</li> <li><code>undefined</code> - Act as ignore, except that files in a directory that begins with a dot are <strong>NOT</strong> ignored.</li> </ul> <h5 id="fallthrough">fallthrough</h5> <p>When this option is <code>true</code>, client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call <code>next()</code> to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke <code>next(err)</code>.</p> <p>Set this option to <code>true</code> so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.</p> <p>Use <code>false</code> 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.</p> <h5 id="setHeaders">setHeaders</h5> <p>For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.</p> <p>The signature of the function is:</p> <pre><code class="language-js">fn(res, path, stat) </code></pre> <p>Arguments:</p> <ul> <li><code>res</code>, the <a href="#res">response object</a>.</li> <li><code>path</code>, the file path that is being sent.</li> <li><code>stat</code>, the <code>stat</code> object of the file that is being sent.</li> </ul> <h4 id="example.of.express.static">Example of express.static</h4> <p>Here is an example of using the <code>express.static</code> middleware function with an elaborate options object:</p> <pre><code class="language-js">var options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders: function (res, path, stat) { res.set('x-timestamp', Date.now()) } } app.use(express.static('public', options)) </code></pre> </section> <section> <h3 id="express.text" class="h2">express.text([options])</h3> <div class="doc-box doc-info"> <p>This middleware is available in Express v4.17.0 onwards.</p> </div> <p>This is a built-in middleware function in Express. It parses incoming request payloads into a string and is based on <a href="/resources/middleware/body-parser.html">body-parser</a>.</p> <p>Returns middleware that parses all bodies as a string and only looks at requests where the <code>Content-Type</code> header matches the <code>type</code> option. This parser accepts any Unicode encoding of the body and supports automatic inflation of <code>gzip</code> and <code>deflate</code> encodings.</p> <p>A new <code>body</code> string containing the parsed data is populated on the <code>request</code> object after the middleware (i.e. <code>req.body</code>), or an empty object (<code>{}</code>) if there was no body to parse, the <code>Content-Type</code> was not matched, or an error occurred.</p> <div class="doc-box doc-warn"> <p>As <code>req.body</code>’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, <code>req.body.trim()</code> may fail in multiple ways, for example stacking multiple parsers <code>req.body</code> may be from a different parser. Testing that <code>req.body</code> is a string before calling string methods is recommended.</p> </div> <p>The following table describes the properties of the optional <code>options</code> object.</p> <table> <thead> <tr> <th>Property</th> <th>Description</th> <th>Type</th> <th>Default</th> </tr> </thead> <tbody> <tr> <td><code>defaultCharset</code></td> <td>Specify the default character set for the text content if the charset is not specified in the <code>Content-Type</code> header of the request.</td> <td>String</td> <td><code>"utf-8"</code></td> </tr> <tr> <td><code>inflate</code></td> <td>Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>limit</code></td> <td>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 <a href="https://www.npmjs.com/package/bytes">bytes</a> library for parsing.</td> <td>Mixed</td> <td><code>"100kb"</code></td> </tr> <tr> <td><code>type</code></td> <td>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, <code>type</code> option is passed directly to the <a href="https://www.npmjs.org/package/type-is#readme">type-is</a> library and this can be an extension name (like <code>txt</code>), a mime type (like <code>text/plain</code>), or a mime type with a wildcard (like <code>*/*</code> or <code>text/*</code>). If a function, the <code>type</code> option is called as <code>fn(req)</code> and the request is parsed if it returns a truthy value.</td> <td>Mixed</td> <td><code>"text/plain"</code></td> </tr> <tr> <td><code>verify</code></td> <td>This option, if supplied, is called as <code>verify(req, res, buf, encoding)</code>, where <code>buf</code> is a <code>Buffer</code> of the raw request body and <code>encoding</code> is the encoding of the request. The parsing can be aborted by throwing an error.</td> <td>Function</td> <td><code>undefined</code></td> </tr> </tbody> </table> </section> <section> <h3 id="express.urlencoded" class="h2">express.urlencoded([options])</h3> <div class="doc-box doc-info"> <p>This middleware is available in Express v4.16.0 onwards.</p> </div> <p>This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on <a href="/resources/middleware/body-parser.html">body-parser</a>.</p> <p>Returns middleware that only parses urlencoded bodies and only looks at requests where the <code>Content-Type</code> header matches the <code>type</code> option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of <code>gzip</code> and <code>deflate</code> encodings.</p> <p>A new <code>body</code> object containing the parsed data is populated on the <code>request</code> object after the middleware (i.e. <code>req.body</code>), or an empty object (<code>{}</code>) if there was no body to parse, the <code>Content-Type</code> was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when <code>extended</code> is <code>false</code>), or any type (when <code>extended</code> is <code>true</code>).</p> <div class="doc-box doc-warn"> <p>As <code>req.body</code>’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, <code>req.body.foo.toString()</code> may fail in multiple ways, for example <code>foo</code> may not be there or may not be a string, and <code>toString</code> may not be a function and instead a string or other user-input.</p> </div> <p>The following table describes the properties of the optional <code>options</code> object.</p> <table> <thead> <tr> <th>Property</th> <th>Description</th> <th>Type</th> <th>Default</th> </tr> </thead> <tbody> <tr> <td><code>extended</code></td> <td>This option allows to choose between parsing the URL-encoded data with the <code>querystring</code> library (when <code>false</code>) or the <code>qs</code> library (when <code>true</code>). 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 <a href="https://www.npmjs.org/package/qs#readme">see the qs library</a>.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>inflate</code></td> <td>Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.</td> <td>Boolean</td> <td><code>true</code></td> </tr> <tr> <td><code>limit</code></td> <td>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 <a href="https://www.npmjs.com/package/bytes">bytes</a> library for parsing.</td> <td>Mixed</td> <td><code>"100kb"</code></td> </tr> <tr> <td><code>parameterLimit</code></td> <td>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.</td> <td>Number</td> <td><code>1000</code></td> </tr> <tr> <td><code>type</code></td> <td>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, <code>type</code> option is passed directly to the <a href="https://www.npmjs.org/package/type-is#readme">type-is</a> library and this can be an extension name (like <code>urlencoded</code>), a mime type (like <code>application/x-www-form-urlencoded</code>), or a mime type with a wildcard (like <code>*/x-www-form-urlencoded</code>). If a function, the <code>type</code> option is called as <code>fn(req)</code> and the request is parsed if it returns a truthy value.</td> <td>Mixed</td> <td><code>"application/x-www-form-urlencoded"</code></td> </tr> <tr> <td><code>verify</code></td> <td>This option, if supplied, is called as <code>verify(req, res, buf, encoding)</code>, where <code>buf</code> is a <code>Buffer</code> of the raw request body and <code>encoding</code> is the encoding of the request. The parsing can be aborted by throwing an error.</td> <td>Function</td> <td><code>undefined</code></td> </tr> </tbody> </table> </section> <h2 id="app">Application</h2> <p>The <code>app</code> object conventionally denotes the Express application. Create it by calling the top-level <code>express()</code> function exported by the Express module:</p> <pre><code class="language-js">var express = require('express') var app = express() app.get('/', function (req, res) { res.send('hello world') }) app.listen(3000) </code></pre> <p>The <code>app</code> object has methods for</p> <ul> <li>Routing HTTP requests; see for example, <a href="#app.METHOD">app.METHOD</a> and <a href="#app.param">app.param</a>.</li> <li>Configuring middleware; see <a href="#app.route">app.route</a>.</li> <li>Rendering HTML views; see <a href="#app.render">app.render</a>.</li> <li>Registering a template engine; see <a href="#app.engine">app.engine</a>.</li> </ul> <p>It also has settings (properties) that affect how the application behaves; for more information, see <a href="#app.settings.table">Application settings</a>.</p> <div class="doc-box doc-info"> <p>The Express application object can be referred from the <a href="#req">request object</a> and the <a href="#res">response object</a> as <code>req.app</code>, and <code>res.app</code>, respectively.</p> </div> <h3 id="app.properties">Properties</h3> <section> <h3 id="app.locals">app.locals</h3> <p>The <code>app.locals</code> object has properties that are local variables within the application, and will be available in templates rendered with <a href="#res.render">res.render</a>.</p> <div class="doc-box doc-warn"> <p>The <code>locals</code> object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations.</p> </div> <pre><code class="language-js">console.dir(app.locals.title) // =&gt; 'My App' console.dir(app.locals.email) // =&gt; 'me@myapp.com' </code></pre> <p>Once set, the value of <code>app.locals</code> properties persist throughout the life of the application, in contrast with <a href="#res.locals">res.locals</a> properties that are valid only for the lifetime of the request.</p> <p>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 <code>req.app.locals</code> (see <a href="#req.app">req.app</a>)</p> <pre><code class="language-js">app.locals.title = 'My App' app.locals.strftime = require('strftime') app.locals.email = 'me@myapp.com' </code></pre> </section> <section> <h3 id="app.mountpath">app.mountpath</h3> <p>The <code>app.mountpath</code> property contains one or more path patterns on which a sub-app was mounted.</p> <div class="doc-box doc-info"> <p>A sub-app is an instance of <code>express</code> that may be used for handling the request to a route.</p> </div> <pre><code class="language-js">var express = require('express') var app = express() // the main app var admin = express() // the sub app admin.get('/', function (req, res) { console.log(admin.mountpath) // /admin res.send('Admin Homepage') }) app.use('/admin', admin) // mount the sub app </code></pre> <p>It is similar to the <a href="#req.baseUrl">baseUrl</a> property of the <code>req</code> object, except <code>req.baseUrl</code> returns the matched URL path, instead of the matched patterns.</p> <p>If a sub-app is mounted on multiple path patterns, <code>app.mountpath</code> returns the list of patterns it is mounted on, as shown in the following example.</p> <pre><code class="language-js">var admin = express() admin.get('/', function (req, res) { console.dir(admin.mountpath) // [ '/adm*n', '/manager' ] res.send('Admin Homepage') }) var secret = express() secret.get('/', function (req, res) { console.log(secret.mountpath) // /secr*t res.send('Admin Secret') }) admin.use('/secr*t', secret) // load the 'secret' router on '/secr*t', on the 'admin' sub app app.use(['/adm*n', '/manager'], admin) // load the 'admin' router on '/adm*n' and '/manager', on the parent app </code></pre> </section> <h3 id="app.events">Events</h3> <section> <h3 id="app.onmount">app.on('mount', callback(parent))</h3> <p>The <code>mount</code> event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.</p> <div class="doc-box doc-info"> <p><strong>NOTE</strong></p> <p>Sub-apps will:</p> <ul> <li>Not inherit the value of settings that have a default value. You must set the value in the sub-app.</li> <li>Inherit the value of settings with no default value.</li> </ul> <p>For details, see <a href="/en/4x/api.html#app.settings.table">Application settings</a>.</p> </div> <pre><code class="language-js">var admin = express() admin.on('mount', function (parent) { console.log('Admin Mounted') console.log(parent) // refers to the parent app }) admin.get('/', function (req, res) { res.send('Admin Homepage') }) app.use('/admin', admin) </code></pre> </section> <h3 id="app.methods">Methods</h3> <section> <h3 id="app.all">app.all(path, callback [, callback ...])</h3> <p>This method is like the standard <a href="#app.METHOD">app.METHOD()</a> methods, except it matches all HTTP verbs.</p> <h4> Arguments</h4> <table class="doctable" border="1" style="padding-left: 20px;"> <tr> <th>Argument </th> <th> Description </th> <th style="width: 100px;"> Default </th> </tr> <tr> <td><code>path</code></td> <td> The path for which the middleware function is invoked; can be any of: <ul> <li>A string representing a path.</li> <li>A path pattern.</li> <li>A regular expression pattern to match paths.</li> <li>An array of combinations of any of the above.</li> </ul> For examples, see <a href="#path-examples">Path examples</a>. </td> <td>'/' (root path)</td> </tr> <tr> <td> <code>callback</code></td> <td> Callback functions; can be: <ul> <li>A middleware function.</li> <li>A series of middleware functions (separated by commas).</li> <li>An array of middleware functions.</li> <li>A combination of all of the above.</li> </ul> <p> You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke <code>next('route')</code> 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. </p><p> Since <a href="#router">router</a> and <a href="#application">app</a> implement the middleware interface, you can use them as you would any other middleware function. </p><p> For examples, see <a href="#middleware-callback-function-examples">Middleware callback function examples</a>. </p> </td> <td> None </td> </tr></table> <h4 id="examples">Examples</h4> <p>The following callback is executed for requests to <code>/secret</code> whether using GET, POST, PUT, DELETE, or any other HTTP request method:</p> <pre><code class="language-js">app.all('/secret', function (req, res, next) { console.log('Accessing the secret section ...') next() // pass control to the next handler }) </code></pre> <p>The <code>app.all()</code> 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: <code>loadUser</code> can perform a task, then call <code>next()</code> to continue matching subsequent routes.</p> <pre><code class="language-js">app.all('*', requireAuthentication, loadUser) </code></pre> <p>Or the equivalent:</p> <pre><code class="language-js">app.all('*', requireAuthentication) app.all('*', loadUser) </code></pre> <p>Another example is white-listed “global” functionality. The example is similar to the ones above, but it only restricts paths that start with “/api”:</p> <pre><code class="language-js">app.all('/api/*', requireAuthentication) </code></pre> </section> <section> <h3 id="app.delete.method">app.delete(path, callback [, callback ...])</h3> <p>Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the <a href="/en/guide/routing.html">routing guide</a>.</p> <h4> Arguments</h4> <table class="doctable" border="1" style="padding-left: 20px;"> <tr> <th>Argument </th> <th> Description </th> <th style="width: 100px;"> Default </th> </tr> <tr> <td><code>path</code></td> <td> The path for which the middleware function is invoked; can be any of: <ul> <li>A string representing a path.</li> <li>A path pattern.</li> <li>A regular expression pattern to match paths.</li> <li>An array of combinations of any of the above.</li> </ul> For examples, see <a href="#path-examples">Path examples</a>. </td> <td>'/' (root path)</td> </tr> <tr> <td> <code>callback</code></td> <td> Callback functions; can be: <ul> <li>A middleware function.</li> <li>A series of middleware functions (separated by commas).</li> <li>An array of middleware functions.</li> <li>A combination of all of the above.</li> </ul> <p> You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke <code>next('route')</code> 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. </p><p> Since <a href="#router">router</a> and <a href="#application">app</a> implement the middleware interface, you can use them as you would any other middleware function. </p><p> For examples, see <a href="#middleware-callback-function-examples">Middleware callback function examples</a>. </p> </td> <td> None </td> </tr></table> <h4 id="example">Example</h4> <pre><code class="language-js">app.delete('/', function (req, res) { res.send('DELETE request to homepage') }) </code></pre> </section> <section> <h3 id="app.disable">app.disable(name)</h3> <p>Sets the Boolean setting <code>name</code> to <code>false</code>, where <code>name</code> is one of the properties from the <a href="#app.settings.table">app settings table</a>. Calling <code>app.set('foo', false)</code> for a Boolean property is the same as calling <code>app.disable('foo')</code>.</p> <p>For example:</p> <pre><code class="language-js">app.disable('trust proxy') app.get('trust proxy') // =&gt; false </code></pre> </section> <section> <h3 id="app.disabled">app.disabled(name)</h3> <p>Returns <code>true</code> if the Boolean setting <code>name</code> is disabled (<code>false</code>), where <code>name</code> is one of the properties from the <a href="#app.settings.table">app settings table</a>.</p> <pre><code class="language-js">app.disabled('trust proxy') // =&gt; true app.enable('trust proxy') app.disabled('trust proxy') // =&gt; false </code></pre> </section> <section> <h3 id="app.enable">app.enable(name)</h3> <p>Sets the Boolean setting <code>name</code> to <code>true</code>, where <code>name</code> is one of the properties from the <a href="#app.settings.table">app settings table</a>. Calling <code>app.set('foo', true)</code> for a Boolean property is the same as calling <code>app.enable('foo')</code>.</p> <pre><code class="language-js">app.enable('trust proxy') app.get('trust proxy') // =&gt; true </code></pre> </section> <section> <h3 id="app.enabled">app.enabled(name)</h3> <p>Returns <code>true</code> if the setting <code>name</code> is enabled (<code>true</code>), where <code>name</code> is one of the properties from the <a href="#app.settings.table">app settings table</a>.</p> <pre><code class="language-js">app.enabled('trust proxy') // =&gt; false app.enable('trust proxy') app.enabled('trust proxy') // =&gt; true </code></pre> </section> <section> <h3 id="app.engine">app.engine(ext, callback)</h3> <p>Registers the given template engine <code>callback</code> as <code>ext</code>.</p> <p>By default, Express will <code>require()</code> 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 <code>require()</code> on subsequent calls to increase performance.</p> <pre><code class="language-js">app.engine('pug', require('pug').__express) </code></pre> <p>Use this method for engines that do not provide <code>.__express</code> out of the box, or if you wish to “map” a different extension to the template engine.</p> <p>For example, to map the EJS template engine to “.html” files:</p> <pre><code class="language-js">app.engine('html', require('ejs').renderFile) </code></pre> <p>In this case, EJS provides a <code>.renderFile()</code> method with the same signature that Express expects: <code>(path, options, callback)</code>, though note that it aliases this method as <code>ejs.__express</code> internally so if you’re using “.ejs” extensions you don’t need to do anything.</p> <p>Some template engines do not follow this convention. The <a href="https://github.com/tj/consolidate.js">consolidate.js</a> library maps Node template engines to follow this convention, so they work seamlessly with Express.</p> <pre><code class="language-js">var engines = require('consolidate') app.engine('haml', engines.haml) app.engine('html', engines.hogan) </code></pre> </section> <section> <h3 id="app.get">app.get(name)</h3> <p>Returns the value of <code>name</code> app setting, where <code>name</code> is one of the strings in the <a href="#app.settings.table">app settings table</a>. For example:</p> <pre><code class="language-js">app.get('title') // =&gt; undefined app.set('title', 'My Site') app.get('title') // =&gt; "My Site" </code></pre> </section> <section> <h3 id="app.get.method">app.get(path, callback [, callback ...])</h3> <p>Routes HTTP GET requests to the specified path with the specified callback functions.</p> <h4> Arguments</h4> <table class="doctable" border="1" style="padding-left: 20px;"> <tr> <th>Argument </th> <th> Description </th> <th style="width: 100px;"> Default </th> </tr> <tr> <td><code>path</code></td> <td> The path for which the middleware function is invoked; can be any of: <ul> <li>A string representing a path.</li> <li>A path pattern.</li> <li>A regular expression pattern to match paths.</li> <li>An array of combinations of any of the above.</li> </ul> For examples, see <a href="#path-examples">Path examples</a>. </td> <td>'/' (root path)</td> </tr> <tr> <td> <code>callback</code></td> <td> Callback functions; can be: <ul> <li>A middleware function.</li> <li>A series of middleware functions (separated by commas).</li> <li>An array of middleware functions.</li> <li>A combination of all of the above.</li> </ul> <p> You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke <code>next('route')</code> 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. </p><p> Since <a href="#router">router</a> and <a href="#application">app</a> implement the middleware interface, you can use them as you would any other middleware function. </p><p> For examples, see <a href="#middleware-callback-function-examples">Middleware callback function examples</a>. </p> </td> <td> None </td> </tr></table> <p>For more information, see the <a href="/en/guide/routing.html">routing guide</a>.</p> <h4 id="example-1">Example</h4> <pre><code class="language-js">app.get('/', function (req, res) { res.send('GET request to homepage') }) </code></pre> </section> <section> <h3 id="app.listen_path_callback">app.listen(path, [callback])</h3> <p>Starts a UNIX socket and listens for connections on the given path. This method is identical to Node’s <a href="https://nodejs.org/api/http.html#http_server_listen">http.Server.listen()</a>.</p> <pre><code class="language-js">var express = require('express') var app = express() app.listen('/tmp/sock') </code></pre> <h3 id="app.listen">app.listen([port[, host[, backlog]]][, callback])</h3> <p>Binds and listens for connections on the specified host and port. This method is identical to Node’s <a href="https://nodejs.org/api/http.html#http_server_listen">http.Server.listen()</a>.</p> <p>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.).</p> <pre><code class="language-js">var express = require('express') var app = express() app.listen(3000) </code></pre> <p>The <code>app</code> returned by <code>express()</code> is in fact a JavaScript <code>Function</code>, 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):</p> <pre><code class="language-js">var express = require('express') var https = require('https') var http = require('http') var app = express() http.createServer(app).listen(80) https.createServer(options, app).listen(443) </code></pre> <p>The <code>app.listen()</code> method returns an <a href="https://nodejs.org/api/http.html#http_class_http_server">http.Server</a> object and (for HTTP) is a convenience method for the following:</p> <pre><code class="language-js">app.listen = function () { var server = http.createServer(this) return server.listen.apply(server, arguments) } </code></pre> <div class="doc-box doc-info"> <p class="doc-info-title"><i class="fa fa-lg fa-info-circle"></i> Note</p> <p>All the forms of Node’s <a href="https://nodejs.org/api/http.html#http_server_listen">http.Server.listen()</a> method are in fact actually supported.</p> </div> </section> <section> <h3 id="app.METHOD">app.METHOD(path, callback [, callback ...])</h3> <p>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 <code>app.get()</code>, <code>app.post()</code>, <code>app.put()</code>, and so on. See <a href="#routing-methods">Routing methods</a> below for the complete list.</p> <h4> Arguments</h4> <table class="doctable" border="1" style="padding-left: 20px;"> <tr> <th>Argument </th> <th> Description </th> <th style="width: 100px;"> Default </th> </tr> <tr> <td><code>path</code></td> <td> The path for which the middleware function is invoked; can be any of: <ul> <li>A string representing a path.</li> <li>A path pattern.</li> <li>A regular expression pattern to match paths.</li> <li>An array of combinations of any of the above.</li> </ul> For examples, see <a href="#path-examples">Path examples</a>. </td> <td>'/' (root path)</td> </tr> <tr> <td> <code>callback</code></td> <td> Callback functions; can be: <ul> <li>A middleware function.</li> <li>A series of middleware functions (separated by commas).</li> <li>An array of middleware functions.</li> <li>A combination of all of the above.</li> </ul> <p> You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke <code>next('route')</code> 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. </p><p> Since <a href="#router">router</a> and <a href="#application">app</a> implement the middleware interface, you can use them as you would any other middleware function. </p><p> For examples, see <a href="#middleware-callback-function-examples">Middleware callback function examples</a>. </p> </td> <td> None </td> </tr></table> <h4 id="routing-methods">Routing methods</h4> <p>Express supports the following routing methods corresponding to the HTTP methods of the same names:</p> <table style="border: 0px; background: none"> <tr> <td style="background: none; border: 0px;"> <ul> <li><code>checkout</code></li> <li><code>copy</code></li> <li><code>delete</code></li> <li><code>get</code></li> <li><code>head</code></li> <li><code>lock</code></li> <li><code>merge</code></li> <li><code>mkactivity</code></li> </ul> </td> <td style="background: none; border: 0px;"> <ul> <li><code>mkcol</code></li> <li><code>move</code></li> <li><code>m-search</code></li> <li><code>notify</code></li> <li><code>options</code></li> <li><code>patch</code></li> <li><code>post</code></li> </ul> </td> <td style="background: none; border: 0px;"> <ul> <li><code>purge</code></li> <li><code>put</code></li> <li><code>report</code></li> <li><code>search</code></li> <li><code>subscribe</code></li> <li><code>trace</code></li> <li><code>unlock</code></li> <li><code>unsubscribe</code></li> </ul> </td> </tr> </table> <p>The API documentation has explicit entries only for the most popular HTTP methods <code>app.get()</code>, <code>app.post()</code>, <code>app.put()</code>, and <code>app.delete()</code>. However, the other methods listed above work in exactly the same way.</p> <p>To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, <code>app['m-search']('/', function ...</code>.</p> <div class="doc-box doc-info"> <p>The <code>app.get()</code> function is automatically called for the HTTP <code>HEAD</code> method in addition to the <code>GET</code> method if <code>app.head()</code> was not called for the path before <code>app.get()</code>.</p> </div> <p>The method, <code>app.all()</code>, is not derived from any HTTP method and loads middleware at the specified path for <em>all</em> HTTP request methods. For more information, see <a href="#app.all">app.all</a>.</p> <p>For more information on routing, see the <a href="/en/guide/routing.html">routing guide</a>.</p> </section> <section> <h3 id="app.param">app.param([name], callback)</h3> <p>Add callback triggers to <a href="/en/guide/routing.html#route-parameters">route parameters</a>, where <code>name</code> is the name of the parameter or an array of them, and <code>callback</code> 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.</p> <p>If <code>name</code> is an array, the <code>callback</code> 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 <code>next</code> inside the callback will call the callback for the next declared parameter. For the last parameter, a call to <code>next</code> will call the next middleware in place for the route currently being processed, just like it would if <code>name</code> were just a string.</p> <p>For example, when <code>:user</code> is present in a route path, you may map user loading logic to automatically provide <code>req.user</code> to the route, or perform validations on the parameter input.</p> <pre><code class="language-js">app.param('user', function (req, res, next, id) { // try to get the user details from the User model and attach it to the request object User.find(id, function (err, user) { if (err) { next(err) } else if (user) { req.user = user next() } else { next(new Error('failed to load user')) } }) }) </code></pre> <p>Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on <code>app</code> will be triggered only by route parameters defined on <code>app</code> routes.</p> <p>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.</p> <pre><code class="language-js">app.param('id', function (req, res, next, id) { console.log('CALLED ONLY ONCE') next() }) app.get('/user/:id', function (req, res, next) { console.log('although this matches') next() }) app.get('/user/:id', function (req, res) { console.log('and this matches too') res.end() }) </code></pre> <p>On <code>GET /user/42</code>, the following is printed:</p> <pre><code>CALLED ONLY ONCE although this matches and this matches too </code></pre> <pre><code class="language-js">app.param(['id', 'page'], function (req, res, next, value) { console.log('CALLED ONLY ONCE with', value) next() }) app.get('/user/:id/:page', function (req, res, next) { console.log('although this matches') next() }) app.get('/user/:id/:page', function (req, res) { console.log('and this matches too') res.end() }) </code></pre> <p>On <code>GET /user/42/3</code>, the following is printed:</p> <pre><code>CALLED ONLY ONCE with 42 CALLED ONLY ONCE with 3 although this matches and this matches too </code></pre> <div class="doc-box doc-warn"> <p>The following section describes <code>app.param(callback)</code>, which is deprecated as of v4.11.0.</p> </div> <p>The behavior of the <code>app.param(name, callback)</code> method can be altered entirely by passing only a function to <code>app.param()</code>. This function is a custom implementation of how <code>app.param(name, callback)</code> should behave - it accepts two parameters and must return a middleware.</p> <p>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.</p> <p>The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.</p> <p>In this example, the <code>app.param(name, callback)</code> signature is modified to <code>app.param(name, accessId)</code>. Instead of accepting a name and a callback, <code>app.param()</code> will now accept a name and a number.</p> <pre><code class="language-js">var express = require('express') var app = express() // customizing the behavior of app.param() app.param(function (param, option) { return function (req, res, next, val) { if (val === option) { next() } else { next('route') } } }) // using the customized app.param() app.param('id', 1337) // route to trigger the capture app.get('/user/:id', function (req, res) { res.send('OK') }) app.listen(3000, function () { console.log('Ready') }) </code></pre> <p>In this example, the <code>app.param(name, callback)</code> 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.</p> <pre><code class="language-js">app.param(function (param, validator) { return function (req, res, next, val) { if (validator(val)) { next() } else { next('route') } } }) app.param('id', function (candidate) { return !isNaN(parseFloat(candidate)) &amp;&amp; isFinite(candidate) }) </code></pre> <div class="doc-box doc-info"> <p>The ‘<code>.</code>’ character can’t be used to capture a character in your capturing regexp. For example you can’t use <code>'/user-.+/'</code> to capture <code>'users-gami'</code>, use <code>[\\s\\S]</code> or <code>[\\w\\W]</code> instead (as in <code>'/user-[\\s\\S]+/'</code>.</p> <p>Examples:</p> <pre><code class="language-js">// captures '1-a_6' but not '543-azser-sder' router.get('/[0-9]+-[[\\w]]*', function (req, res, next) { next() }) // captures '1-a_6' and '543-az(ser"-sder' but not '5-a s' router.get('/[0-9]+-[[\\S]]*', function (req, res, next) { next() }) // captures all (equivalent to '.*') router.get('[[\\s\\S]]*', function (req, res, next) { next() }) </code></pre> </div> </section> <section> <h3 id="app.path">app.path()</h3> <p>Returns the canonical path of the app, a string.</p> <pre><code class="language-js">var app = express() var blog = express() var blogAdmin = express() app.use('/blog', blog) blog.use('/admin', blogAdmin) console.dir(app.path()) // '' console.dir(blog.path()) // '/blog' console.dir(blogAdmin.path()) // '/blog/admin' </code></pre> <p>The behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use <a href="#req.baseUrl">req.baseUrl</a> to get the canonical path of the app.</p> </section> <section> <h3 id="app.post.method">app.post(path, callback [, callback ...])</h3> <p>Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the <a href="/en/guide/routing.html">routing guide</a>.</p> <h4> Arguments</h4> <table class="doctable" border="1" style="padding-left: 20px;"> <tr> <th>Argument </th> <th> Description </th> <th style="width: 100px;"> Default </th> </tr> <tr> <td><code>path</code></td> <td> The path for which the middleware function is invoked; can be any of: <ul> <li>A string representing a path.</li> <li>A path pattern.</li> <li>A regular expression pattern to match paths.</li> <li>An array of combinations of any of the above.</li> </ul> For examples, see <a href="#path-examples">Path examples</a>. </td> <td>'/' (root path)</td> </tr> <tr> <td> <code>callback</code></td> <td> Callback functions; can be: <ul> <li>A middleware function.</li> <li>A series of middleware functions (separated by commas).</li> <li>An array of middleware functions.</li> <li>A combination of all of the above.</li> </ul> <p> You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke <code>next('route')</code> 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. </p><p> Since <a href="#router">router</a> and <a href="#application">app</a> implement the middleware interface, you can use them as you would any other middleware function. </p><p> For examples, see <a href="#middleware-callback-function-examples">Middleware callback function examples</a>. </p> </td> <td> None </td> </tr></table> <h4 id="example-2">Example</h4> <pre><code class="language-js">app.post('/', function (req, res) { res.send('POST request to homepage') }) </code></pre> </section> <section> <h3 id="app.put.method">app.put(path, callback [, callback ...])</h3> <p>Routes HTTP PUT requests to the specified path with the specified callback functions.</p> <h4> Arguments</h4> <table class="doctable" border="1" style="padding-left: 20px;"> <tr> <th>Argument </th> <th> Description </th> <th style="width: 100px;"> Default </th> </tr> <tr> <td><code>path</code></td> <td> The path for which the middleware function is invoked; can be any of: <ul> <li>A string representing a path.</li> <li>A path pattern.</li> <li>A regular expression pattern to match paths.</li> <li>An array of combinations of any of the above.</li> </ul> For examples, see <a href="#path-examples">Path examples</a>. </td> <td>'/' (root path)</td> </tr> <tr> <td> <code>callback</code></td> <td> Callback functions; can be: <ul> <li>A middleware function.</li> <li>A series of middleware functions (separated by commas).</li> <li>An array of middleware functions.</li> <li>A combination of all of the above.</li> </ul> <p> You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke <code>next('route')</code> 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. </p><p> Since <a href="#router">router</a> and <a href="#application">app</a> implement the middleware interface, you can use them as you would any other middleware function. </p><p> For examples, see <a href="#middleware-callback-function-examples">Middleware callback function examples</a>. </p> </td> <td> None </td> </tr></table> <h4 id="example-3">Example</h4> <pre><code class="language-js">app.put('/', function (req, res) { res.send('PUT request to homepage') }) </code></pre> </section> <section> <h3 id="app.render">app.render(view, [locals], callback)</h3> <p>Returns the rendered HTML of a view via the <code>callback</code> function. It accepts an optional parameter that is an object containing local variables for the view. It is like <a href="#res.render">res.render()</a>, except it cannot send the rendered view to the client on its own.</p> <div class="doc-box doc-info"> <p>Think of <code>app.render()</code> as a utility function for generating rendered view strings. Internally <code>res.render()</code> uses <code>app.render()</code> to render views.</p> </div> <div class="doc-box doc-warn"> <p>The <code>view</code> 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.</p> </div> <div class="doc-box doc-warn"> <p>The <code>locals</code> object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations.</p> </div> <div class="doc-box doc-notice"> <p>The local variable <code>cache</code> is reserved for enabling view cache. Set it to <code>true</code>, if you want to cache view during development; view caching is enabled in production by default.</p> </div> <pre><code class="language-js">app.render('email', function (err, html) { // ... }) app.render('email', { name: 'Tobi' }, function (err, html) { // ... }) </code></pre> </section> <section> <h3 id="app.route">app.route(path)</h3> <p>Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use <code>app.route()</code> to avoid duplicate route names (and thus typo errors).</p> <pre><code class="language-js">var app = express() app.route('/events') .all(function (req, res, next) { // runs for all HTTP verbs first // think of it as route specific middleware! }) .get(function (req, res, next) { res.json({}) }) .post(function (req, res, next) { // maybe add a new event... }) </code></pre> </section> <section> <h3 id="app.set">app.set(name, value)</h3> <p>Assigns setting <code>name</code> to <code>value</code>. 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 <a href="#app.settings.table">app settings table</a>.</p> <p>Calling <code>app.set('foo', true)</code> for a Boolean property is the same as calling <code>app.enable('foo')</code>. Similarly, calling <code>app.set('foo', false)</code> for a Boolean property is the same as calling <code>app.disable('foo')</code>.</p> <p>Retrieve the value of a setting with <a href="#app.get"><code>app.get()</code></a>.</p> <pre><code class="language-js">app.set('title', 'My Site') app.get('title') // "My Site" </code></pre> <h4 id="app.settings.table">Application Settings</h4> <p>The following table lists application settings.</p> <p>Note that sub-apps will:</p> <ul> <li>Not inherit the value of settings that have a default value. You must set the value in the sub-app.</li> <li>Inherit the value of settings with no default value; these are explicitly noted in the table below.</li> </ul> <p>Exceptions: Sub-apps will inherit the value of <code>trust proxy</code> even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of <code>view cache</code> in production (when <code>NODE_ENV</code> is “production”).</p> <div class="table-scroller"> <table class="doctable" border="1"> <thead><tr><th id="app-settings-property">Property</th><th>Type</th><th>Description</th><th>Default</th></tr></thead> <tbody> <tr> <td> <p><code>case sensitive routing</code></p> </td> <td>Boolean</td> <td><p>Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.</p> <p><b>NOTE</b>: Sub-apps will inherit the value of this setting.</p> </td> <td>N/A (undefined) </td> </tr> <tr> <td> <p><code>env</code></p> </td> <td>String</td> <td> <p>Environment mode. Be sure to set to “production” in a production environment; see <a href="/en/advanced/best-practice-performance.html#env">Production best practices: performance and reliability</a>.</p> </td> <td> <p><code>process.env.NODE_ENV</code> (<code>NODE_ENV</code> environment variable) or “development” if <code>NODE_ENV</code> is not set.</p> </td> </tr> <tr> <td> <p><code>etag</code></p> </td> <td>Varied</td> <td> <p>Set the ETag response header. For possible values, see the <a href="#etag.options.table"><code>etag</code> options table</a>.</p> <p><a href="http://en.wikipedia.org/wiki/HTTP_ETag">More about the HTTP ETag header</a>.</p> </td> <td> <p><code>weak</code></p> </td> </tr> <tr> <td> <p><code>jsonp callback name</code></p> </td> <td>String</td> <td>Specifies the default JSONP callback name.</td> <td> <p>“callback”</p> </td> </tr> <tr> <td> <p><code>json escape</code></p> </td> <td>Boolean</td> <td> <p>Enable escaping JSON responses from the <code>res.json</code>, <code>res.jsonp</code>, and <code>res.send</code> APIs. This will escape the characters <code>&lt;</code>, <code>&gt;</code>, and <code>&amp;</code> as Unicode escape sequences in JSON. The purpose of this it to assist with <a href="https://blog.mozilla.org/security/2017/07/18/web-service-audits-firefox-accounts/">mitigating certain types of persistent XSS attacks</a> when clients sniff responses for HTML.</p> <p><b>NOTE</b>: Sub-apps will inherit the value of this setting.</p> </td> <td>N/A (undefined)</td> </tr> <tr> <td> <p><code>json replacer</code></p> </td> <td>Varied</td> <td>The <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter">'replacer' argument used by `JSON.stringify`</a>. <p><b>NOTE</b>: Sub-apps will inherit the value of this setting.</p> </td> <td>N/A (undefined) </td> </tr> <tr> <td> <p><code>json spaces</code></p> </td> <td>Varied</td> <td>The <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument">'space' argument used by `JSON.stringify`</a>. This is typically set to the number of spaces to use to indent prettified JSON. <p><b>NOTE</b>: Sub-apps will inherit the value of this setting.</p> </td> <td>N/A (undefined)</td> </tr> <tr> <td> <p><code>query parser</code></p> </td> <td>Varied</td> <td> <p>Disable query parsing by setting the value to <code>false</code>, or set the query parser to use either “simple” or “extended” or a custom query string parsing function.</p> <p>The simple query parser is based on Node’s native query parser, <a href="http://nodejs.org/api/querystring.html">querystring</a>.</p> <p>The extended query parser is based on <a href="https://www.npmjs.org/package/qs">qs</a>.</p> <p>A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values.</p> </td> <td>"extended"</td> </tr> <tr> <td> <p><code>strict routing</code></p> </td> <td>Boolean</td> <td><p>Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same.</p> <p><b>NOTE</b>: Sub-apps will inherit the value of this setting.</p> </td> <td>N/A (undefined) </td> </tr> <tr> <td> <p><code>subdomain offset</code></p> </td> <td>Number</td> <td>The number of dot-separated parts of the host to remove to access subdomain.</td> <td>2</td> </tr> <tr> <td> <p><code>trust proxy</code></p> </td> <td>Varied</td> <td> <p>Indicates the app is behind a front-facing proxy, and to use the <code>X-Forwarded-*</code> headers to determine the connection and the IP address of the client. NOTE: <code>X-Forwarded-*</code> headers are easily spoofed and the detected IP addresses are unreliable.</p> <p> When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the <a href="#trust.proxy.options.table">trust proxy options table</a>. </p> <p> The `trust proxy` setting is implemented using the <a href="https://www.npmjs.org/package/proxy-addr">proxy-addr</a> package. For more information, see its documentation. </p> <p> <b>NOTE</b>: Sub-apps <i>will</i> inherit the value of this setting, even though it has a default value. </p> </td> <td> <p><code>false</code> (disabled)</p> </td> </tr> <tr> <td> <p><code>views</code></p> </td> <td>String or Array</td> <td>A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.</td> <td> <p><code>process.cwd() + '/views'</code></p> </td> </tr> <tr> <td> <p><code>view cache</code></p> </td> <td>Boolean</td> <td><p>Enables view template compilation caching.</p> <p><b>NOTE</b>: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").</p> </td> <td> <p><code>true</code> in production, otherwise undefined.</p> </td> </tr> <tr> <td> <p><code>view engine</code></p> </td> <td>String</td> <td>The default engine extension to use when omitted. <p><b>NOTE</b>: Sub-apps will inherit the value of this setting.</p> </td> <td>N/A (undefined)</td> </tr> <tr> <td> <p><code>x-powered-by</code></p> </td> <td>Boolean</td> <td>Enables the "X-Powered-By: Express" HTTP header.</td> <td> <p><code>true</code></p> </td> </tr> </tbody> </table> <h5 id="trust.proxy.options.table">Options for `trust proxy` setting</h5> <p> Read <a href="/en/guide/behind-proxies.html">Express behind proxies</a> for more information. </p> <table class="doctable" border="1"> <thead><tr><th>Type</th><th>Value</th></tr></thead> <tbody> <tr> <td>Boolean</td> <td> <p>If <code>true</code>, the client’s IP address is understood as the left-most entry in the <code>X-Forwarded-*</code> header.</p> <p>If <code>false</code>, the app is understood as directly facing the Internet and the client’s IP address is derived from <code>req.connection.remoteAddress</code>. This is the default setting.</p> </td> </tr> <tr> <td>String<br />String containing comma-separated values<br />Array of strings </td> <td> <p>An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are:</p> <ul> <li>loopback - <code>127.0.0.1/8</code>, <code>::1/128</code></li> <li>linklocal - <code>169.254.0.0/16</code>, <code>fe80::/10</code></li> <li>uniquelocal - <code>10.0.0.0/8</code>, <code>172.16.0.0/12</code>, <code>192.168.0.0/16</code>, <code>fc00::/7</code></li> </ul> <p>Set IP addresses in any of the following ways:</p> <p>Specify a single subnet:</p> <pre><code class="language-js">app.set('trust proxy', 'loopback') </code></pre> <p>Specify a subnet and an address:</p> <pre><code class="language-js">app.set('trust proxy', 'loopback, 123.123.123.123') </code></pre> <p>Specify multiple subnets as CSV:</p> <pre><code class="language-js">app.set('trust proxy', 'loopback, linklocal, uniquelocal') </code></pre> <p>Specify multiple subnets as an array:</p> <pre><code class="language-js">app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) </code></pre> <p>When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address.</p> </td> </tr> <tr> <td>Number</td> <td> <p>Trust the <i>n</i><sup>th</sup> hop from the front-facing proxy server as the client.</p> </td> </tr> <tr> <td>Function</td> <td> <p>Custom trust implementation. Use this only if you know what you are doing.</p> <pre><code class="language-js">app.set('trust proxy', function (ip) { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs else return false }) </code></pre> </td> </tr> </tbody> </table> <h5 id="etag.options.table">Options for `etag` setting</h5> <p> <strong>NOTE</strong>: These settings apply only to dynamic files, not static files. The <a href="#express.static">express.static</a> middleware ignores these settings. </p> <p> The ETag functionality is implemented using the <a href="https://www.npmjs.org/package/etag">etag</a> package. For more information, see its documentation. </p> <table class="doctable" border="1"> <thead><tr><th>Type</th><th>Value</th></tr></thead> <tbody> <tr> <td>Boolean</td> <td> <p><code>true</code> enables weak ETag. This is the default setting.<br /> <code>false</code> disables ETag altogether.</p> </td> </tr> <tr> <td>String</td> <td> If "strong", enables strong ETag.<br /> If "weak", enables weak ETag. </td> </tr> <tr> <td>Function</td> <td> <p>Custom ETag function implementation. Use this only if you know what you are doing.</p> <pre><code class="language-js">app.set('etag', function (body, encoding) { return generateHash(body, encoding) // consider the function is defined }) </code></pre> </td> </tr> </tbody> </table> </div> </section> <section> <h3 id="app.use">app.use([path,] callback [, callback...])</h3> <p>Mounts the specified <a href="/en/guide/using-middleware.html">middleware</a> function or functions at the specified path: the middleware function is executed when the base of the requested path matches <code>path</code>.</p> <h4> Arguments</h4> <table class="doctable" border="1" style="padding-left: 20px;"> <tr> <th>Argument </th> <th> Description </th> <th style="width: 100px;"> Default </th> </tr> <tr> <td><code>path</code></td> <td> The path for which the middleware function is invoked; can be any of: <ul> <li>A string representing a path.</li> <li>A path pattern.</li> <li>A regular expression pattern to match paths.</li> <li>An array of combinations of any of the above.</li> </ul> For examples, see <a href="#path-examples">Path examples</a>. </td> <td>'/' (root path)</td> </tr> <tr> <td> <code>callback</code></td> <td> Callback functions; can be: <ul> <li>A middleware function.</li> <li>A series of middleware functions (separated by commas).</li> <li>An array of middleware functions.</li> <li>A combination of all of the above.</li> </ul> <p> You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke <code>next('route')</code> 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. </p><p> Since <a href="#router">router</a> and <a href="#application">app</a> implement the middleware interface, you can use them as you would any other middleware function. </p><p> For examples, see <a href="#middleware-callback-function-examples">Middleware callback function examples</a>. </p> </td> <td> None </td> </tr></table> <h4 id="description">Description</h4> <p>A route will match any path that follows its path immediately with a “<code>/</code>”. For example: <code>app.use('/apple', ...)</code> will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.</p> <p>Since <code>path</code> 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 <em>every</em> request to the app:</p> <pre><code class="language-js">app.use(function (req, res, next) { console.log('Time: %d', Date.now()) next() }) </code></pre> <div class="doc-box doc-info"> <p><strong>NOTE</strong></p> <p>Sub-apps will:</p> <ul> <li>Not inherit the value of settings that have a default value. You must set the value in the sub-app.</li> <li>Inherit the value of settings with no default value.</li> </ul> <p>For details, see <a href="/en/4x/api.html#app.settings.table">Application settings</a>.</p> </div> <p>Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.</p> <pre><code class="language-js">// this middleware will not allow the request to go beyond it app.use(function (req, res, next) { res.send('Hello World') }) // requests will never reach this route app.get('/', function (req, res) { res.send('Welcome') }) </code></pre> <p><strong>Error-handling middleware</strong></p> <p>Error-handling middleware always takes <em>four</em> arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the <code>next</code> object, you must specify it to maintain the signature. Otherwise, the <code>next</code> object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: <a href="/en/guide/error-handling.html">Error handling</a>.</p> <p>Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature <code>(err, req, res, next)</code>):</p> <pre><code class="language-js">app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') }) </code></pre> <h4 id="path-examples">Path examples</h4> <p>The following table provides some simple examples of valid <code>path</code> values for mounting middleware.</p> <div class="table-scroller"> <table class="doctable" border="1"> <thead> <tr> <th>Type</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>Path</td> <td> <p>This will match paths starting with <code>/abcd</code>:</p> <pre><code class="language-js">app.use('/abcd', function (req, res, next) { next() }) </code></pre> </td> </tr> <tr> <td>Path Pattern</td> <td> <p>This will match paths starting with <code>/abcd</code> and <code>/abd</code>:</p> <pre><code class="language-js">app.use('/abc?d', function (req, res, next) { next() }) </code></pre> <p>This will match paths starting with <code>/abcd</code>, <code>/abbcd</code>, <code>/abbbbbcd</code>, and so on:</p> <pre><code class="language-js">app.use('/ab+cd', function (req, res, next) { next() }) </code></pre> <p>This will match paths starting with <code>/abcd</code>, <code>/abxcd</code>, <code>/abFOOcd</code>, <code>/abbArcd</code>, and so on:</p> <pre><code class="language-js">app.use('/ab*cd', function (req, res, next) { next() }) </code></pre> <p>This will match paths starting with <code>/ad</code> and <code>/abcd</code>:</p> <pre><code class="language-js">app.use('/a(bc)?d', function (req, res, next) { next() }) </code></pre> </td> </tr> <tr> <td>Regular Expression</td> <td> <p>This will match paths starting with <code>/abc</code> and <code>/xyz</code>:</p> <pre><code class="language-js">app.use(/\/abc|\/xyz/, function (req, res, next) { next() }) </code></pre> </td> </tr> <tr> <td>Array</td> <td> <p>This will match paths starting with <code>/abcd</code>, <code>/xyza</code>, <code>/lmn</code>, and <code>/pqr</code>:</p> <pre><code class="language-js">app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) { next() }) </code></pre> </td> </tr> </tbody> </table> </div> <h4 id="middleware-callback-function-examples">Middleware callback function examples</h4> <p>The following table provides some simple examples of middleware functions that can be used as the <code>callback</code> argument to <code>app.use()</code>, <code>app.METHOD()</code>, and <code>app.all()</code>.</p> <table class="doctable" border="1"> <thead> <tr> <th>Usage</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>Single Middleware</td> <td> <p>You can define and mount a middleware function locally.</p> <pre><code class="language-js">app.use(function (req, res, next) { next() }) </code></pre> <p>A router is valid middleware.</p> <pre><code class="language-js">var router = express.Router() router.get('/', function (req, res, next) { next() }) app.use(router) </code></pre> <p>An Express app is valid middleware.</p> <pre><code class="language-js">var subApp = express() subApp.get('/', function (req, res, next) { next() }) app.use(subApp) </code></pre> </td> </tr> <tr> <td>Series of Middleware</td> <td> <p>You can specify more than one middleware function at the same mount path.</p> <pre><code class="language-js">var r1 = express.Router() r1.get('/', function (req, res, next) { next() }) var r2 = express.Router() r2.get('/', function (req, res, next) { next() }) app.use(r1, r2) </code></pre> </td> </tr> <tr> <td>Array</td> <td> <p>Use an array to group middleware logically.</p> <pre><code class="language-js">var r1 = express.Router() r1.get('/', function (req, res, next) { next() }) var r2 = express.Router() r2.get('/', function (req, res, next) { next() }) app.use([r1, r2]) </code></pre> </td> </tr> <tr> <td>Combination</td> <td> <p>You can combine all the above ways of mounting middleware.</p> <pre><code class="language-js">function mw1 (req, res, next) { next() } function mw2 (req, res, next) { next() } var r1 = express.Router() r1.get('/', function (req, res, next) { next() }) var r2 = express.Router() r2.get('/', function (req, res, next) { next() }) var subApp = express() subApp.get('/', function (req, res, next) { next() }) app.use(mw1, [mw2, r1, r2], subApp) </code></pre> </td> </tr> </tbody> </table> <p>Following are some examples of using the <a href="/en/guide/using-middleware.html#middleware.built-in">express.static</a> middleware in an Express app.</p> <p>Serve static content for the app from the “public” directory in the application directory:</p> <pre><code class="language-js">// GET /style.css etc app.use(express.static(path.join(__dirname, 'public'))) </code></pre> <p>Mount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:</p> <pre><code class="language-js">// GET /static/style.css etc. app.use('/static', express.static(path.join(__dirname, 'public'))) </code></pre> <p>Disable logging for static content requests by loading the logger middleware after the static middleware:</p> <pre><code class="language-js">app.use(express.static(path.join(__dirname, 'public'))) app.use(logger()) </code></pre> <p>Serve static files from multiple directories, but give precedence to “./public” over the others:</p> <pre><code class="language-js">app.use(express.static(path.join(__dirname, 'public'))) app.use(express.static(path.join(__dirname, 'files'))) app.use(express.static(path.join(__dirname, 'uploads'))) </code></pre> </section> <h2 id="req">Request</h2> <p>The <code>req</code> 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 <code>req</code> (and the HTTP response is <code>res</code>) but its actual name is determined by the parameters to the callback function in which you’re working.</p> <p>For example:</p> <pre><code class="language-js">app.get('/user/:id', function (req, res) { res.send('user ' + req.params.id) }) </code></pre> <p>But you could just as well have:</p> <pre><code class="language-js">app.get('/user/:id', function (request, response) { response.send('user ' + request.params.id) }) </code></pre> <p>The <code>req</code> object is an enhanced version of Node’s own request object and supports all <a href="https://nodejs.org/api/http.html#http_class_http_incomingmessage">built-in fields and methods</a>.</p> <h3 id="req.properties">Properties</h3> <div class="doc-box doc-notice"> <p>In Express 4, <code>req.files</code> is no longer available on the <code>req</code> object by default. To access uploaded files on the <code>req.files</code> object, use multipart-handling middleware like <a href="https://www.npmjs. com/package/busboy">busboy</a>, <a href="https://www.npmjs.com/package/multer">multer</a>, <a href="https://www.npmjs.com/package/formidable">formidable</a>, <a href="https://www.npmjs.com/package/multiparty">multiparty</a>, <a href="https://www.npmjs.com/package/connect-multiparty">connect-multiparty</a>, or <a href="https://www.npmjs.com/package/pez">pez</a>.</p> </div> <section> <h3 id="req.app">req.app</h3> <p>This property holds a reference to the instance of the Express application that is using the middleware.</p> <p>If you follow the pattern in which you create a module that just exports a middleware function and <code>require()</code> it in your main file, then the middleware can access the Express instance via <code>req.app</code></p> <p>For example:</p> <pre><code class="language-js">// index.js app.get('/viewdirectory', require('./mymiddleware.js')) </code></pre> <pre><code class="language-js">// mymiddleware.js module.exports = function (req, res) { res.send('The views directory is ' + req.app.get('views')) } </code></pre> </section> <section> <h3 id="req.baseUrl">req.baseUrl</h3> <p>The URL path on which a router instance was mounted.</p> <p>The <code>req.baseUrl</code> property is similar to the <a href="#app.mountpath">mountpath</a> property of the <code>app</code> object, except <code>app.mountpath</code> returns the matched path pattern(s).</p> <p>For example:</p> <pre><code class="language-js">var greet = express.Router() greet.get('/jp', function (req, res) { console.log(req.baseUrl) // /greet res.send('Konnichiwa!') }) app.use('/greet', greet) // load the router on '/greet' </code></pre> <p>Even if you use a path pattern or a set of path patterns to load the router, the <code>baseUrl</code> property returns the matched string, not the pattern(s). In the following example, the <code>greet</code> router is loaded on two path patterns.</p> <pre><code class="language-js">app.use(['/gre+t', '/hel{2}o'], greet) // load the router on '/gre+t' and '/hel{2}o' </code></pre> <p>When a request is made to <code>/greet/jp</code>, <code>req.baseUrl</code> is “/greet”. When a request is made to <code>/hello/jp</code>, <code>req.baseUrl</code> is “/hello”.</p> </section> <section> <h3 id="req.body">req.body</h3> <p>Contains key-value pairs of data submitted in the request body. By default, it is <code>undefined</code>, and is populated when you use body-parsing middleware such as <a href="#express.json"><code>express.json()</code></a> or <a href="#express.urlencoded"><code>express.urlencoded()</code></a>.</p> <div class="doc-box doc-warn"> <p>As <code>req.body</code>’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, <code>req.body.foo.toString()</code> may fail in multiple ways, for example <code>foo</code> may not be there or may not be a string, and <code>toString</code> may not be a function and instead a string or other user-input.</p> </div> <p>The following example shows how to use body-parsing middleware to populate <code>req.body</code>.</p> <pre><code class="language-js">var express = require('express') var app = express() app.use(express.json()) // for parsing application/json app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded app.post('/profile', function (req, res, next) { console.log(req.body) res.json(req.body) }) </code></pre> </section> <section> <h3 id="req.cookies">req.cookies</h3> <p>When using <a href="https://www.npmjs.com/package/cookie-parser">cookie-parser</a> middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to <code>{}</code>.</p> <pre><code class="language-js">// Cookie: name=tj console.dir(req.cookies.name) // =&gt; 'tj' </code></pre> <p>If the cookie has been signed, you have to use <a href="#req.signedCookies">req.signedCookies</a>.</p> <p>For more information, issues, or concerns, see <a href="https://github.com/expressjs/cookie-parser">cookie-parser</a>.</p> </section> <section> <h3 id="req.fresh">req.fresh</h3> <p>When the response is still “fresh” in the client’s cache <code>true</code> is returned, otherwise <code>false</code> is returned to indicate that the client cache is now stale and the full response should be sent.</p> <p>When a client sends the <code>Cache-Control: no-cache</code> request header to indicate an end-to-end reload request, this module will return <code>false</code> to make handling these requests transparent.</p> <p>Further details for how cache validation works can be found in the <a href="https://tools.ietf.org/html/rfc7234">HTTP/1.1 Caching Specification</a>.</p> <pre><code class="language-js">console.dir(req.fresh) // =&gt; true </code></pre> </section> <section> <h3 id="req.hostname">req.hostname</h3> <p>Contains the hostname derived from the <code>Host</code> HTTP header.</p> <p>When the <a href="/4x/api.html#trust.proxy.options.table"><code>trust proxy</code> setting</a> does not evaluate to <code>false</code>, this property will instead get the value from the <code>X-Forwarded-Host</code> header field. This header can be set by the client or by the proxy.</p> <p>If there is more than one <code>X-Forwarded-Host</code> 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.</p> <div class="doc-box doc-info"> <p>Prior to Express v4.17.0, the <code>X-Forwarded-Host</code> could not contain multiple values or be present more than once.</p> </div> <pre><code class="language-js">// Host: "example.com:3000" console.dir(req.hostname) // =&gt; 'example.com' </code></pre> </section> <section> <h3 id="req.ip">req.ip</h3> <p>Contains the remote IP address of the request.</p> <p>When the <a href="/4x/api.html#trust.proxy.options.table"><code>trust proxy</code> setting</a> does not evaluate to <code>false</code>, the value of this property is derived from the left-most entry in the <code>X-Forwarded-For</code> header. This header can be set by the client or by the proxy.</p> <pre><code class="language-js">console.dir(req.ip) // =&gt; '127.0.0.1' </code></pre> </section> <section> <h3 id="req.ips">req.ips</h3> <p>When the <a href="/4x/api.html#trust.proxy.options.table"><code>trust proxy</code> setting</a> does not evaluate to <code>false</code>, this property contains an array of IP addresses specified in the <code>X-Forwarded-For</code> request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.</p> <p>For example, if <code>X-Forwarded-For</code> is <code>client, proxy1, proxy2</code>, <code>req.ips</code> would be <code>["client", "proxy1", "proxy2"]</code>, where <code>proxy2</code> is the furthest downstream.</p> </section> <section> <h3 id="req.method">req.method</h3> <p>Contains a string corresponding to the HTTP method of the request: <code>GET</code>, <code>POST</code>, <code>PUT</code>, and so on.</p> </section> <section> <h3 id="req.originalUrl">req.originalUrl</h3> <div class="doc-box doc-notice"> <p><code>req.url</code> is not a native Express property, it is inherited from Node’s <a href="https://nodejs.org/api/http.html#http_message_url">http module</a>.</p> </div> <p>This property is much like <code>req.url</code>; however, it retains the original request URL, allowing you to rewrite <code>req.url</code> freely for internal routing purposes. For example, the “mounting” feature of <a href="#app.use">app.use()</a> will rewrite <code>req.url</code> to strip the mount point.</p> <pre><code class="language-js">// GET /search?q=something console.dir(req.originalUrl) // =&gt; '/search?q=something' </code></pre> <p><code>req.originalUrl</code> is available both in middleware and router objects, and is a combination of <code>req.baseUrl</code> and <code>req.url</code>. Consider following example:</p> <pre><code class="language-js">app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?sort=desc' console.dir(req.originalUrl) // '/admin/new?sort=desc' console.dir(req.baseUrl) // '/admin' console.dir(req.path) // '/new' next() }) </code></pre> </section> <section> <h3 id="req.params">req.params</h3> <p>This property is an object containing properties mapped to the <a href="/en/guide/routing.html#route-parameters">named route “parameters”</a>. For example, if you have the route <code>/user/:name</code>, then the “name” property is available as <code>req.params.name</code>. This object defaults to <code>{}</code>.</p> <pre><code class="language-js">// GET /user/tj console.dir(req.params.name) // =&gt; 'tj' </code></pre> <p>When you use a regular expression for the route definition, capture groups are provided in the array using <code>req.params[n]</code>, where <code>n</code> is the n<sup>th</sup> capture group. This rule is applied to unnamed wild card matches with string routes such as <code>/file/*</code>:</p> <pre><code class="language-js">// GET /file/javascripts/jquery.js console.dir(req.params[0]) // =&gt; 'javascripts/jquery.js' </code></pre> <p>If you need to make changes to a key in <code>req.params</code>, use the <a href="/en/4x/api.html#app.param">app.param</a> handler. Changes are applicable only to <a href="/en/guide/routing.html#route-parameters">parameters</a> already defined in the route path.</p> <p>Any changes made to the <code>req.params</code> object in a middleware or route handler will be reset.</p> <div class="doc-box doc-info"> <p class="doc-info-title"><i class="fa fa-lg fa-info-circle"></i> Note</p> <p>Express automatically decodes the values in <code>req.params</code> (using <code>decodeURIComponent</code>).</p> </div> </section> <section> <h3 id="req.path">req.path</h3> <p>Contains the path part of the request URL.</p> <pre><code class="language-js">// example.com/users?sort=desc console.dir(req.path) // =&gt; '/users' </code></pre> <div class="doc-box doc-info"> <p>When called from a middleware, the mount point is not included in <code>req.path</code>. See <a href="/4x/api.html#app.use">app.use()</a> for more details.</p> </div> </section> <section> <h3 id="req.protocol">req.protocol</h3> <p>Contains the request protocol string: either <code>http</code> or (for TLS requests) <code>https</code>.</p> <p>When the <a href="#trust.proxy.options.table"><code>trust proxy</code> setting</a> does not evaluate to <code>false</code>, this property will use the value of the <code>X-Forwarded-Proto</code> header field if present. This header can be set by the client or by the proxy.</p> <pre><code class="language-js">console.dir(req.protocol) // =&gt; 'http' </code></pre> </section> <section> <h3 id="req.query">req.query</h3> <p>This property is an object containing a property for each query string parameter in the route. When <a href="#app.settings.table">query parser</a> is set to disabled, it is an empty object <code>{}</code>, otherwise it is the result of the configured query parser.</p> <div class="doc-box doc-warn"> <p>As <code>req.query</code>’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, <code>req.query.foo.toString()</code> may fail in multiple ways, for example <code>foo</code> may not be there or may not be a string, and <code>toString</code> may not be a function and instead a string or other user-input.</p> </div> <p>The value of this property can be configured with the <a href="#app.settings.table">query parser application setting</a> to work how your application needs it. A very popular query string parser is the <a href="https://www.npmjs.org/package/qs"><code>qs</code> module</a>, and this is used by default. The <code>qs</code> module is very configurable with many settings, and it may be desirable to use different settings than the default to populate <code>req.query</code>:</p> <pre><code class="language-js">var qs = require('qs') app.set('query parser', function (str) { return qs.parse(str, { /* custom options */ }) }) </code></pre> <p>Check out the <a href="#app.settings.table">query parser application setting</a> documentation for other customization options.</p> </section> <section> <h3 id="req.res">req.res</h3> <p>This property holds a reference to the <a href="#res">response object</a> that relates to this request object.</p> </section> <section> <h3 id="req.route">req.route</h3> <p>Contains the currently-matched route, a string. For example:</p> <pre><code class="language-js">app.get('/user/:id?', function userIdHandler (req, res) { console.log(req.route) res.send('GET') }) </code></pre> <p>Example output from the previous snippet:</p> <pre><code>{ path: '/user/:id?', stack: [ { handle: [Function: userIdHandler], name: 'userIdHandler', params: undefined, path: undefined, keys: [], regexp: /^\/?$/i, method: 'get' } ], methods: { get: true } } </code></pre> </section> <section> <h3 id="req.secure">req.secure</h3> <p>A Boolean property that is true if a TLS connection is established. Equivalent to:</p> <pre><code class="language-js">console.dir(req.protocol === 'https') // =&gt; true </code></pre> </section> <section> <h3 id="req.signedCookies">req.signedCookies</h3> <p>When using <a href="https://www.npmjs.com/package/cookie-parser">cookie-parser</a> 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 <code>req.cookie</code> 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).</p> <p>If no signed cookies are sent, the property defaults to <code>{}</code>.</p> <pre><code class="language-js">// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3 console.dir(req.signedCookies.user) // =&gt; 'tobi' </code></pre> <p>For more information, issues, or concerns, see <a href="https://github.com/expressjs/cookie-parser">cookie-parser</a>.</p> </section> <section> <h3 id="req.stale">req.stale</h3> <p>Indicates whether the request is “stale,” and is the opposite of <code>req.fresh</code>. For more information, see <a href="#req.fresh">req.fresh</a>.</p> <pre><code class="language-js">console.dir(req.stale) // =&gt; true </code></pre> </section> <section> <h3 id="req.subdomains">req.subdomains</h3> <p>An array of subdomains in the domain name of the request.</p> <pre><code class="language-js">// Host: "tobi.ferrets.example.com" console.dir(req.subdomains) // =&gt; ['ferrets', 'tobi'] </code></pre> <p>The application property <code>subdomain offset</code>, which defaults to 2, is used for determining the beginning of the subdomain segments. To change this behavior, change its value using <a href="/en/4x/api.html#app.set">app.set</a>.</p> </section> <section> <h3 id="req.xhr">req.xhr</h3> <p>A Boolean property that is <code>true</code> if the request’s <code>X-Requested-With</code> header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery.</p> <pre><code class="language-js">console.dir(req.xhr) // =&gt; true </code></pre> </section> <h3 id="req.methods">Methods</h3> <section> <h3 id="req.accepts">req.accepts(types)</h3> <p>Checks if the specified content types are acceptable, based on the request’s <code>Accept</code> HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns <code>false</code> (in which case, the application should respond with <code>406 "Not Acceptable"</code>).</p> <p>The <code>type</code> 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 <em>best</em> match (if any).</p> <pre><code class="language-js">// Accept: text/html req.accepts('html') // =&gt; "html" // Accept: text/*, application/json req.accepts('html') // =&gt; "html" req.accepts('text/html') // =&gt; "text/html" req.accepts(['json', 'text']) // =&gt; "json" req.accepts('application/json') // =&gt; "application/json" // Accept: text/*, application/json req.accepts('image/png') req.accepts('png') // =&gt; false // Accept: text/*;q=.5, application/json req.accepts(['html', 'json']) // =&gt; "json" </code></pre> <p>For more information, or if you have issues or concerns, see <a href="https://github.com/expressjs/accepts">accepts</a>.</p> </section> <section> <h3 id="req.acceptsCharsets">req.acceptsCharsets(charset [, ...])</h3> <p>Returns the first accepted charset of the specified character sets, based on the request’s <code>Accept-Charset</code> HTTP header field. If none of the specified charsets is accepted, returns <code>false</code>.</p> <p>For more information, or if you have issues or concerns, see <a href="https://github.com/expressjs/accepts">accepts</a>.</p> </section> <section> <h3 id="req.acceptsEncodings">req.acceptsEncodings(encoding [, ...])</h3> <p>Returns the first accepted encoding of the specified encodings, based on the request’s <code>Accept-Encoding</code> HTTP header field. If none of the specified encodings is accepted, returns <code>false</code>.</p> <p>For more information, or if you have issues or concerns, see <a href="https://github.com/expressjs/accepts">accepts</a>.</p> </section> <section> <h3 id="req.acceptsLanguages">req.acceptsLanguages([lang, ...])</h3> <p>Returns the first accepted language of the specified languages, based on the request’s <code>Accept-Language</code> HTTP header field. If none of the specified languages is accepted, returns <code>false</code>.</p> <p>If no <code>lang</code> argument is given, then <code>req.acceptsLanguages()</code> returns all languages from the HTTP <code>Accept-Language</code> header as an <code>Array</code>.</p> <p>For more information, or if you have issues or concerns, see <a href="https://github.com/expressjs/accepts">accepts</a>.</p> <p>Express (4.x) source: <a href="https://github.com/expressjs/express/blob/4.x/lib/request.js#L179">request.js line 179</a></p> <p>Accepts (1.3) source: <a href="https://github.com/jshttp/accepts/blob/f69c19e459bd501e59fb0b1a40b7471bb578113a/index.js#L195">index.js line 195</a></p> </section> <section> <h3 id="req.get">req.get(field)</h3> <p>Returns the specified HTTP request header field (case-insensitive match). The <code>Referrer</code> and <code>Referer</code> fields are interchangeable.</p> <pre><code class="language-js">req.get('Content-Type') // =&gt; "text/plain" req.get('content-type') // =&gt; "text/plain" req.get('Something') // =&gt; undefined </code></pre> <p>Aliased as <code>req.header(field)</code>.</p> </section> <section> <h3 id="req.is">req.is(type)</h3> <p>Returns the matching content type if the incoming request’s “Content-Type” HTTP header field matches the MIME type specified by the <code>type</code> parameter. If the request has no body, returns <code>null</code>. Returns <code>false</code> otherwise.</p> <pre><code class="language-js">// With Content-Type: text/html; charset=utf-8 req.is('html') // =&gt; 'html' req.is('text/html') // =&gt; 'text/html' req.is('text/*') // =&gt; 'text/*' // When Content-Type is application/json req.is('json') // =&gt; 'json' req.is('application/json') // =&gt; 'application/json' req.is('application/*') // =&gt; 'application/*' req.is('html') // =&gt; false </code></pre> <p>For more information, or if you have issues or concerns, see <a href="https://github.com/expressjs/type-is">type-is</a>.</p> </section> <section> <h3 id="req.param">req.param(name [, defaultValue])</h3> <div class="doc-box doc-warn"> <p>Deprecated. Use either <code>req.params</code>, <code>req.body</code> or <code>req.query</code>, as applicable.</p> </div> <p>Returns the value of param <code>name</code> when present.</p> <pre><code class="language-js">// ?name=tobi req.param('name') // =&gt; "tobi" // POST name=tobi req.param('name') // =&gt; "tobi" // /user/tobi for /user/:name req.param('name') // =&gt; "tobi" </code></pre> <p>Lookup is performed in the following order:</p> <ul> <li><code>req.params</code></li> <li><code>req.body</code></li> <li><code>req.query</code></li> </ul> <p>Optionally, you can specify <code>defaultValue</code> to set a default value if the parameter is not found in any of the request objects.</p> <div class="doc-box doc-warn"> <p>Direct access to <code>req.body</code>, <code>req.params</code>, and <code>req.query</code> should be favoured for clarity - unless you truly accept input from each object.</p> <p>Body-parsing middleware must be loaded for <code>req.param()</code> to work predictably. Refer <a href="#req.body">req.body</a> for details.</p> </div> </section> <section> <h3 id="req.range">req.range(size[, options])</h3> <p><code>Range</code> header parser.</p> <p>The <code>size</code> parameter is the maximum size of the resource.</p> <p>The <code>options</code> parameter is an object that can have the following properties.</p> <table> <thead> <tr> <th>Property</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>combine</code></td> <td>Boolean</td> <td>Specify if overlapping &amp; adjacent ranges should be combined, defaults to <code>false</code>. When <code>true</code>, ranges will be combined and returned as if they were specified that way in the header.</td> </tr> </tbody> </table> <p>An array of ranges will be returned or negative numbers indicating an error parsing.</p> <ul> <li><code>-2</code> signals a malformed header string</li> <li><code>-1</code> signals an unsatisfiable range</li> </ul> <pre><code class="language-js">// parse header from request var range = req.range(1000) // the type of the range if (range.type === 'bytes') { // the ranges range.forEach(function (r) { // do something with r.start and r.end }) } </code></pre> </section> <h2 id="res">Response</h2> <p>The <code>res</code> object represents the HTTP response that an Express app sends when it gets an HTTP request.</p> <p>In this documentation and by convention, the object is always referred to as <code>res</code> (and the HTTP request is <code>req</code>) but its actual name is determined by the parameters to the callback function in which you’re working.</p> <p>For example:</p> <pre><code class="language-js">app.get('/user/:id', function (req, res) { res.send('user ' + req.params.id) }) </code></pre> <p>But you could just as well have:</p> <pre><code class="language-js">app.get('/user/:id', function (request, response) { response.send('user ' + request.params.id) }) </code></pre> <p>The <code>res</code> object is an enhanced version of Node’s own response object and supports all <a href="https://nodejs.org/api/http.html#http_class_http_serverresponse">built-in fields and methods</a>.</p> <h3 id="res.properties">Properties</h3> <section> <h3 id="res.app">res.app</h3> <p>This property holds a reference to the instance of the Express application that is using the middleware.</p> <p><code>res.app</code> is identical to the <a href="#req.app">req.app</a> property in the request object.</p> </section> <section> <h3 id="res.headersSent">res.headersSent</h3> <p>Boolean property that indicates if the app sent HTTP headers for the response.</p> <pre><code class="language-js">app.get('/', function (req, res) { console.dir(res.headersSent) // false res.send('OK') console.dir(res.headersSent) // true }) </code></pre> </section> <section> <h3 id="res.locals">res.locals</h3> <p>Use this property to set variables accessible in templates rendered with <a href="#res.render">res.render</a>. The variables set on <code>res.locals</code> are available within a single request-response cycle, and will not be shared between requests.</p> <div class="doc-box doc-warn"> <p>The <code>locals</code> object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations.</p> </div> <p>In order to keep local variables for use in template rendering between requests, use <a href="#app.locals">app.locals</a> instead.</p> <p>This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.</p> <pre><code class="language-js">app.use(function (req, res, next) { // Make `user` and `authenticated` available in templates res.locals.user = req.user res.locals.authenticated = !req.user.anonymous next() }) </code></pre> </section> <h3 id="res.methods">Methods</h3> <section> <h3 id="res.append">res.append(field [, value])</h3> <div class="doc-box doc-info"> <p class="doc-info-title"><i class="fa fa-lg fa-info-circle"></i> Note</p> <p><code>res.append()</code> is supported by Express v4.11.0+</p> </div> <p>Appends the specified <code>value</code> to the HTTP response header <code>field</code>. If the header is not already set, it creates the header with the specified value. The <code>value</code> parameter can be a string or an array.</p> <div class="doc-box doc-info"> <p class="doc-info-title"><i class="fa fa-lg fa-info-circle"></i> Note</p> <p>calling <code>res.set()</code> after <code>res.append()</code> will reset the previously-set header value.</p> </div> <pre><code class="language-js">res.append('Link', ['&lt;http://localhost/&gt;', '&lt;http://localhost:3000/&gt;']) res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly') res.append('Warning', '199 Miscellaneous warning') </code></pre> </section> <section> <h3 id="res.attachment">res.attachment([filename])</h3> <p>Sets the HTTP response <code>Content-Disposition</code> header field to “attachment”. If a <code>filename</code> is given, then it sets the Content-Type based on the extension name via <code>res.type()</code>, and sets the <code>Content-Disposition</code> “filename=” parameter.</p> <pre><code class="language-js">res.attachment() // Content-Disposition: attachment res.attachment('path/to/logo.png') // Content-Disposition: attachment; filename="logo.png" // Content-Type: image/png </code></pre> </section> <section> <h3 id="res.cookie">res.cookie(name, value [, options])</h3> <p>Sets cookie <code>name</code> to <code>value</code>. The <code>value</code> parameter may be a string or object converted to JSON.</p> <p>The <code>options</code> parameter is an object that can have the following properties.</p> <table> <thead> <tr> <th>Property</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>domain</code></td> <td>String</td> <td>Domain name for the cookie. Defaults to the domain name of the app.</td> </tr> <tr> <td><code>encode</code></td> <td>Function</td> <td>A synchronous function used for cookie value encoding. Defaults to <code>encodeURIComponent</code>.</td> </tr> <tr> <td><code>expires</code></td> <td>Date</td> <td>Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie.</td> </tr> <tr> <td><code>httpOnly</code></td> <td>Boolean</td> <td>Flags the cookie to be accessible only by the web server.</td> </tr> <tr> <td><code>maxAge</code></td> <td>Number</td> <td>Convenient option for setting the expiry time relative to the current time in milliseconds.</td> </tr> <tr> <td><code>path</code></td> <td>String</td> <td>Path for the cookie. Defaults to “/”.</td> </tr> <tr> <td><code>partitioned</code></td> <td>Boolean</td> <td>Indicates that the cookie should be stored using partitioned storage. See <a href="https://developer.mozilla.org/en-US/docs/Web/Privacy/Partitioned_cookies">Cookies Having Independent Partitioned State (CHIPS)</a> for more details.</td> </tr> <tr> <td><code>priority</code></td> <td>String</td> <td>Value of the “Priority” <strong>Set-Cookie</strong> attribute.</td> </tr> <tr> <td><code>secure</code></td> <td>Boolean</td> <td>Marks the cookie to be used with HTTPS only.</td> </tr> <tr> <td><code>signed</code></td> <td>Boolean</td> <td>Indicates if the cookie should be signed.</td> </tr> <tr> <td><code>sameSite</code></td> <td>Boolean or String</td> <td>Value of the “SameSite” <strong>Set-Cookie</strong> attribute. More information at <a href="https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1">https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1</a>.</td> </tr> </tbody> </table> <div class="doc-box doc-notice"> <p>All <code>res.cookie()</code> does is set the HTTP <code>Set-Cookie</code> header with the options provided. Any option not specified defaults to the value stated in <a href="http://tools.ietf.org/html/rfc6265">RFC 6265</a>.</p> </div> <p>For example:</p> <pre><code class="language-js">res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }) res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }) </code></pre> <p>You can set multiple cookies in a single response by calling <code>res.cookie</code> multiple times, for example:</p> <pre><code class="language-js">res .status(201) .cookie('access_token', 'Bearer ' + token, { expires: new Date(Date.now() + 8 * 3600000) // cookie will be removed after 8 hours }) .cookie('test', 'test') .redirect(301, '/admin') </code></pre> <p>The <code>encode</code> option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions.</p> <p>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.</p> <pre><code class="language-js">// Default encoding res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' }) // Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/' // Custom encoding res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String }) // Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;' </code></pre> <p>The <code>maxAge</code> option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the second example above.</p> <pre><code class="language-js">res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) </code></pre> <p>You can pass an object as the <code>value</code> parameter; it is then serialized as JSON and parsed by <code>bodyParser()</code> middleware.</p> <pre><code class="language-js">res.cookie('cart', { items: [1, 2, 3] }) res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 }) </code></pre> <p>When using <a href="https://www.npmjs.com/package/cookie-parser">cookie-parser</a> middleware, this method also supports signed cookies. Simply include the <code>signed</code> option set to <code>true</code>. Then <code>res.cookie()</code> will use the secret passed to <code>cookieParser(secret)</code> to sign the value.</p> <pre><code class="language-js">res.cookie('name', 'tobi', { signed: true }) </code></pre> <p>Later you may access this value through the <a href="#req.signedCookies">req.signedCookie</a> object.</p> </section> <section> <h3 id="res.clearCookie">res.clearCookie(name [, options])</h3> <p>Clears the cookie specified by <code>name</code>. For details about the <code>options</code> object, see <a href="#res.cookie">res.cookie()</a>.</p> <div class="doc-box doc-notice"> <p>Web browsers and other compliant clients will only clear the cookie if the given <code>options</code> is identical to those given to <a href="#res.cookie">res.cookie()</a>, excluding <code>expires</code> and <code>maxAge</code>.</p> </div> <pre><code class="language-js">res.cookie('name', 'tobi', { path: '/admin' }) res.clearCookie('name', { path: '/admin' }) </code></pre> </section> <section> <h3 id="res.download">res.download(path [, filename] [, options] [, fn])</h3> <p>Transfers the file at <code>path</code> as an “attachment”. Typically, browsers will prompt the user for download. By default, the <code>Content-Disposition</code> header “filename=” parameter is derived from the <code>path</code> argument, but can be overridden with the <code>filename</code> parameter. If <code>path</code> is relative, then it will be based on the current working directory of the process or the <code>root</code> option, if provided.</p> <div class="doc-box doc-warn"> <p>This API provides access to data on the running file system. Ensure that either (a) the way in which the <code>path</code> argument was constructed is secure if it contains user input or (b) set the <code>root</code> option to the absolute path of a directory to contain access within.</p> <p>When the <code>root</code> option is provided, Express will validate that the relative path provided as <code>path</code> will resolve within the given <code>root</code> option.</p> </div> <p>The following table provides details on the <code>options</code> parameter.</p> <div class="doc-box doc-info"> <p>The optional <code>options</code> argument is supported by Express v4.16.0 onwards.</p> </div> <div class="table-scroller"> <table> <thead> <tr> <th>Property</th> <th>Description</th> <th>Default</th> <th>Availability</th> </tr> </thead> <tbody> <tr> <td><code>maxAge</code></td> <td>Sets the max-age property of the <code>Cache-Control</code> header in milliseconds or a string in <a href="https://www.npmjs.org/package/ms">ms format</a></td> <td>0</td> <td>4.16+</td> </tr> <tr> <td><code>root</code></td> <td>Root directory for relative filenames.</td> <td> </td> <td>4.18+</td> </tr> <tr> <td><code>lastModified</code></td> <td>Sets the <code>Last-Modified</code> header to the last modified date of the file on the OS. Set <code>false</code> to disable it.</td> <td>Enabled</td> <td>4.16+</td> </tr> <tr> <td><code>headers</code></td> <td>Object containing HTTP headers to serve with the file. The header <code>Content-Disposition</code> will be overridden by the <code>filename</code> argument.</td> <td> </td> <td>4.16+</td> </tr> <tr> <td><code>dotfiles</code></td> <td>Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”.</td> <td>“ignore”</td> <td>4.16+</td> </tr> <tr> <td><code>acceptRanges</code></td> <td>Enable or disable accepting ranged requests.</td> <td><code>true</code></td> <td>4.16+</td> </tr> <tr> <td><code>cacheControl</code></td> <td>Enable or disable setting <code>Cache-Control</code> response header.</td> <td><code>true</code></td> <td>4.16+</td> </tr> <tr> <td><code>immutable</code></td> <td>Enable or disable the <code>immutable</code> directive in the <code>Cache-Control</code> response header. If enabled, the <code>maxAge</code> option should also be specified to enable caching. The <code>immutable</code> directive will prevent supported clients from making conditional requests during the life of the <code>maxAge</code> option to check if the file has changed.</td> <td><code>false</code></td> <td>4.16+</td> </tr> </tbody> </table> </div> <p>The method invokes the callback function <code>fn(err)</code> 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.</p> <pre><code class="language-js">res.download('/report-12345.pdf') res.download('/report-12345.pdf', 'report.pdf') res.download('/report-12345.pdf', 'report.pdf', function (err) { if (err) { // Handle error, but keep in mind the response may be partially-sent // so check res.headersSent } else { // decrement a download credit, etc. } }) </code></pre> </section> <section> <h3 id="res.end">res.end([data] [, encoding])</h3> <p>Ends the response process. This method actually comes from Node core, specifically the <a href="https://nodejs.org/api/http.html#http_response_end_data_encoding_callback">response.end() method of http.ServerResponse</a>.</p> <p>Use to quickly end the response without any data. If you need to respond with data, instead use methods such as <a href="#res.send">res.send()</a> and <a href="#res.json">res.json()</a>.</p> <pre><code class="language-js">res.end() res.status(404).end() </code></pre> </section> <section> <h3 id="res.format">res.format(object)</h3> <p>Performs content-negotiation on the <code>Accept</code> HTTP header on the request object, when present. It uses <a href="#req.accepts">req.accepts()</a> 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 <code>default</code> callback.</p> <p>The <code>Content-Type</code> response header is set when a callback is selected. However, you may alter this within the callback using methods such as <code>res.set()</code> or <code>res.type()</code>.</p> <p>The following example would respond with <code>{ "message": "hey" }</code> when the <code>Accept</code> header field is set to “application/json” or “*/json” (however if it is “*/*”, then the response will be “hey”).</p> <pre><code class="language-js">res.format({ 'text/plain': function () { res.send('hey') }, 'text/html': function () { res.send('&lt;p&gt;hey&lt;/p&gt;') }, 'application/json': function () { res.send({ message: 'hey' }) }, default: function () { // log the request and respond with 406 res.status(406).send('Not Acceptable') } }) </code></pre> <p>In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:</p> <pre><code class="language-js">res.format({ text: function () { res.send('hey') }, html: function () { res.send('&lt;p&gt;hey&lt;/p&gt;') }, json: function () { res.send({ message: 'hey' }) } }) </code></pre> </section> <section> <h3 id="res.get">res.get(field)</h3> <p>Returns the HTTP response header specified by <code>field</code>. The match is case-insensitive.</p> <pre><code class="language-js">res.get('Content-Type') // =&gt; "text/plain" </code></pre> </section> <section> <h3 id="res.json">res.json([body])</h3> <p>Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify()</a>.</p> <p>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.</p> <pre><code class="language-js">res.json(null) res.json({ user: 'tobi' }) res.status(500).json({ error: 'message' }) </code></pre> </section> <section> <h3 id="res.jsonp">res.jsonp([body])</h3> <p>Sends a JSON response with JSONP support. This method is identical to <code>res.json()</code>, except that it opts-in to JSONP callback support.</p> <pre><code class="language-js">res.jsonp(null) // =&gt; callback(null) res.jsonp({ user: 'tobi' }) // =&gt; callback({ "user": "tobi" }) res.status(500).jsonp({ error: 'message' }) // =&gt; callback({ "error": "message" }) </code></pre> <p>By default, the JSONP callback name is simply <code>callback</code>. Override this with the <a href="#app.settings.table">jsonp callback name</a> setting.</p> <p>The following are some examples of JSONP responses using the same code:</p> <pre><code class="language-js">// ?callback=foo res.jsonp({ user: 'tobi' }) // =&gt; foo({ "user": "tobi" }) app.set('jsonp callback name', 'cb') // ?cb=foo res.status(500).jsonp({ error: 'message' }) // =&gt; foo({ "error": "message" }) </code></pre> </section> <section> <h3 id="res.links">res.links(links)</h3> <p>Joins the <code>links</code> provided as properties of the parameter to populate the response’s <code>Link</code> HTTP header field.</p> <p>For example, the following call:</p> <pre><code class="language-js">res.links({ next: 'http://api.example.com/users?page=2', last: 'http://api.example.com/users?page=5' }) </code></pre> <p>Yields the following results:</p> <pre><code>Link: &lt;http://api.example.com/users?page=2&gt;; rel="next", &lt;http://api.example.com/users?page=5&gt;; rel="last" </code></pre> </section> <section> <h3 id="res.location">res.location(path)</h3> <p>Sets the response <code>Location</code> HTTP header to the specified <code>path</code> parameter.</p> <pre><code class="language-js">res.location('/foo/bar') res.location('http://example.com') res.location('back') </code></pre> <p>A <code>path</code> value of “back” has a special meaning, it refers to the URL specified in the <code>Referer</code> header of the request. If the <code>Referer</code> header was not specified, it refers to “/”.</p> <p>See also <a href="http://expressjs.com/en/advanced/best-practice-security.html#prevent-open-redirects">Security best practices: Prevent open redirect vulnerabilities</a>.</p> <div class="doc-box doc-warn"> <p>After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the <code>Location</code> header, without any validation.</p> <p>Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the <code>Location</code> header; and redirect the user accordingly.</p> </div> </section> <section> <h3 id="res.redirect">res.redirect([status,] path)</h3> <p>Redirects to the URL derived from the specified <code>path</code>, with specified <code>status</code>, a positive integer that corresponds to an <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP status code</a> . If not specified, <code>status</code> defaults to “302 “Found”.</p> <pre><code class="language-js">res.redirect('/foo/bar') res.redirect('http://example.com') res.redirect(301, 'http://example.com') res.redirect('../login') </code></pre> <p>Redirects can be a fully-qualified URL for redirecting to a different site:</p> <pre><code class="language-js">res.redirect('http://google.com') </code></pre> <p>Redirects can be relative to the root of the host name. For example, if the application is on <code>http://example.com/admin/post/new</code>, the following would redirect to the URL <code>http://example.com/admin</code>:</p> <pre><code class="language-js">res.redirect('/admin') </code></pre> <p>Redirects can be relative to the current URL. For example, from <code>http://example.com/blog/admin/</code> (notice the trailing slash), the following would redirect to the URL <code>http://example.com/blog/admin/post/new</code>.</p> <pre><code class="language-js">res.redirect('post/new') </code></pre> <p>Redirecting to <code>post/new</code> from <code>http://example.com/blog/admin</code> (no trailing slash), will redirect to <code>http://example.com/blog/post/new</code>.</p> <p>If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.</p> <p>Path-relative redirects are also possible. If you were on <code>http://example.com/admin/post/new</code>, the following would redirect to <code>http://example.com/admin/post</code>:</p> <pre><code class="language-js">res.redirect('..') </code></pre> <p>A <code>back</code> redirection redirects the request back to the <a href="http://en.wikipedia.org/wiki/HTTP_referer">referer</a>, defaulting to <code>/</code> when the referer is missing.</p> <pre><code class="language-js">res.redirect('back') </code></pre> <p>See also <a href="http://expressjs.com/en/advanced/best-practice-security.html#prevent-open-redirects">Security best practices: Prevent open redirect vulnerabilities</a>.</p> </section> <section> <h3 id="res.render">res.render(view [, locals] [, callback])</h3> <p>Renders a <code>view</code> and sends the rendered HTML string to the client. Optional parameters:</p> <ul> <li><code>locals</code>, an object whose properties define local variables for the view.</li> <li><code>callback</code>, 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 <code>next(err)</code> internally.</li> </ul> <p>The <code>view</code> 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 <code>views</code> setting. If the path does not contain a file extension, then the <code>view engine</code> 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 <code>require()</code>) and render it using the loaded module’s <code>__express</code> function.</p> <p>For more information, see <a href="/en/guide/using-template-engines.html">Using template engines with Express</a>.</p> <div class="doc-box doc-warn"> <p>The <code>view</code> 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.</p> </div> <div class="doc-box doc-warn"> <p>The <code>locals</code> object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations.</p> </div> <div class="doc-box doc-notice"> <p>The local variable <code>cache</code> enables view caching. Set it to <code>true</code>, to cache the view during development; view caching is enabled in production by default.</p> </div> <pre><code class="language-js">// send the rendered view to the client res.render('index') // if a callback is specified, the rendered HTML string has to be sent explicitly res.render('index', function (err, html) { res.send(html) }) // pass a local variable to the view res.render('user', { name: 'Tobi' }, function (err, html) { // ... }) </code></pre> </section> <section> <h3 id="res.req">res.req</h3> This property holds a reference to the <a href="#req">request object</a> that relates to this response object. </section> <section> <h3 id="res.send">res.send([body])</h3> <p>Sends the HTTP response.</p> <p>The <code>body</code> parameter can be a <code>Buffer</code> object, a <code>String</code>, an object, <code>Boolean</code>, or an <code>Array</code>. For example:</p> <pre><code class="language-js">res.send(Buffer.from('whoop')) res.send({ some: 'json' }) res.send('&lt;p&gt;some html&lt;/p&gt;') res.status(404).send('Sorry, we cannot find that!') res.status(500).send({ error: 'something blew up' }) </code></pre> <p>This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the <code>Content-Length</code> HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.</p> <p>When the parameter is a <code>Buffer</code> object, the method sets the <code>Content-Type</code> response header field to “application/octet-stream”, unless previously defined as shown below:</p> <pre><code class="language-js">res.set('Content-Type', 'text/html') res.send(Buffer.from('&lt;p&gt;some html&lt;/p&gt;')) </code></pre> <p>When the parameter is a <code>String</code>, the method sets the <code>Content-Type</code> to “text/html”:</p> <pre><code class="language-js">res.send('&lt;p&gt;some html&lt;/p&gt;') </code></pre> <p>When the parameter is an <code>Array</code> or <code>Object</code>, Express responds with the JSON representation:</p> <pre><code class="language-js">res.send({ user: 'tobi' }) res.send([1, 2, 3]) </code></pre> </section> <section> <h3 id="res.sendFile">res.sendFile(path [, options] [, fn])</h3> <div class="doc-box doc-info"> <p><code>res.sendFile()</code> is supported by Express v4.8.0 onwards.</p> </div> <p>Transfers the file at the given <code>path</code>. Sets the <code>Content-Type</code> response HTTP header field based on the filename’s extension. Unless the <code>root</code> option is set in the options object, <code>path</code> must be an absolute path to the file.</p> <div class="doc-box doc-warn"> <p>This API provides access to data on the running file system. Ensure that either (a) the way in which the <code>path</code> argument was constructed into an absolute path is secure if it contains user input or (b) set the <code>root</code> option to the absolute path of a directory to contain access within.</p> <p>When the <code>root</code> option is provided, the <code>path</code> argument is allowed to be a relative path, including containing <code>..</code>. Express will validate that the relative path provided as <code>path</code> will resolve within the given <code>root</code> option.</p> </div> <p>The following table provides details on the <code>options</code> parameter.</p> <div class="table-scroller"> <table> <thead> <tr> <th>Property</th> <th>Description</th> <th>Default</th> <th>Availability</th> </tr> </thead> <tbody> <tr> <td><code>maxAge</code></td> <td>Sets the max-age property of the <code>Cache-Control</code> header in milliseconds or a string in <a href="https://www.npmjs.org/package/ms">ms format</a></td> <td>0</td> <td> </td> </tr> <tr> <td><code>root</code></td> <td>Root directory for relative filenames.</td> <td> </td> <td> </td> </tr> <tr> <td><code>lastModified</code></td> <td>Sets the <code>Last-Modified</code> header to the last modified date of the file on the OS. Set <code>false</code> to disable it.</td> <td>Enabled</td> <td>4.9.0+</td> </tr> <tr> <td><code>headers</code></td> <td>Object containing HTTP headers to serve with the file.</td> <td> </td> <td> </td> </tr> <tr> <td><code>dotfiles</code></td> <td>Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”.</td> <td>“ignore”</td> <td> </td> </tr> <tr> <td><code>acceptRanges</code></td> <td>Enable or disable accepting ranged requests.</td> <td><code>true</code></td> <td>4.14+</td> </tr> <tr> <td><code>cacheControl</code></td> <td>Enable or disable setting <code>Cache-Control</code> response header.</td> <td><code>true</code></td> <td>4.14+</td> </tr> <tr> <td><code>immutable</code></td> <td>Enable or disable the <code>immutable</code> directive in the <code>Cache-Control</code> response header. If enabled, the <code>maxAge</code> option should also be specified to enable caching. The <code>immutable</code> directive will prevent supported clients from making conditional requests during the life of the <code>maxAge</code> option to check if the file has changed.</td> <td><code>false</code></td> <td>4.16+</td> </tr> </tbody> </table> </div> <p>The method invokes the callback function <code>fn(err)</code> 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.</p> <p>Here is an example of using <code>res.sendFile</code> with all its arguments.</p> <pre><code class="language-js">app.get('/file/:name', function (req, res, next) { var options = { root: path.join(__dirname, 'public'), dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true } } var fileName = req.params.name res.sendFile(fileName, options, function (err) { if (err) { next(err) } else { console.log('Sent:', fileName) } }) }) </code></pre> <p>The following example illustrates using <code>res.sendFile</code> to provide fine-grained support for serving files:</p> <pre><code class="language-js">app.get('/user/:uid/photos/:file', function (req, res) { var uid = req.params.uid var file = req.params.file req.user.mayViewFilesFrom(uid, function (yes) { if (yes) { res.sendFile('/uploads/' + uid + '/' + file) } else { res.status(403).send("Sorry! You can't see that.") } }) }) </code></pre> <p>For more information, or if you have issues or concerns, see <a href="https://github.com/pillarjs/send">send</a>.</p> </section> <section> <h3 id="res.sendStatus">res.sendStatus(statusCode)</h3> <p>Sets the response HTTP status code to <code>statusCode</code> 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.</p> <pre><code class="language-js">res.sendStatus(404) </code></pre> <div class="doc-box doc-notice"> <p>Some versions of Node.js will throw when <code>res.statusCode</code> is set to an invalid HTTP status code (outside of the range <code>100</code> to <code>599</code>). Consult the HTTP server documentation for the Node.js version being used.</p> </div> <p><a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes">More about HTTP Status Codes</a></p> </section> <section> <h3 id="res.set">res.set(field [, value])</h3> <p>Sets the response’s HTTP header <code>field</code> to <code>value</code>. To set multiple fields at once, pass an object as the parameter.</p> <pre><code class="language-js">res.set('Content-Type', 'text/plain') res.set({ 'Content-Type': 'text/plain', 'Content-Length': '123', ETag: '12345' }) </code></pre> <p>Aliased as <code>res.header(field [, value])</code>.</p> </section> <section> <h3 id="res.status">res.status(code)</h3> <p>Sets the HTTP status for the response. It is a chainable alias of Node’s <a href="http://nodejs.org/api/http.html#http_response_statuscode">response.statusCode</a>.</p> <pre><code class="language-js">res.status(403).end() res.status(400).send('Bad Request') res.status(404).sendFile('/absolute/path/to/404.png') </code></pre> </section> <section> <h3 id="res.type">res.type(type)</h3> <p>Sets the <code>Content-Type</code> HTTP header to the MIME type as determined by the specified <code>type</code>. If <code>type</code> contains the “/” character, then it sets the <code>Content-Type</code> to the exact value of <code>type</code>, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the <code>express.static.mime.lookup()</code> method.</p> <pre><code class="language-js">res.type('.html') // =&gt; 'text/html' res.type('html') // =&gt; 'text/html' res.type('json') // =&gt; 'application/json' res.type('application/json') // =&gt; 'application/json' res.type('png') // =&gt; 'image/png' </code></pre> </section> <section> <h3 id="res.vary">res.vary(field)</h3> <p>Adds the field to the <code>Vary</code> response header, if it is not there already.</p> <pre><code class="language-js">res.vary('User-Agent').render('docs') </code></pre> </section> <h2 id="router">Router</h2> <section> <p>A <code>router</code> object is an 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.</p> <p>A router behaves like middleware itself, so you can use it as an argument to <a href="#app.use">app.use()</a> or as the argument to another router’s <a href="#router.use">use()</a> method.</p> <p>The top-level <code>express</code> object has a <a href="#express.router">Router()</a> method that creates a new <code>router</code> object.</p> <p>Once you’ve created a router object, you can add middleware and HTTP method routes (such as <code>get</code>, <code>put</code>, <code>post</code>, and so on) to it just like an application. For example:</p> <pre><code class="language-js">// invoked for any requests passed to this router router.use(function (req, res, next) { // .. some logic here .. like any other middleware next() }) // will handle any request that ends in /events // depends on where the router is "use()'d" router.get('/events', function (req, res, next) { // .. }) </code></pre> <p>You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.</p> <pre><code class="language-js">// only requests to /calendar/* will be sent to our "router" app.use('/calendar', router) </code></pre> <p>Keep in mind that any middleware applied to a router will run for all requests on that router’s path, even those that aren’t part of the router.</p> </section> <h3 id="router.methods">Methods</h3> <section> <h3 id="router.all">router.all(path, [callback, ...] callback)</h3> <p>This method is just like the <code>router.METHOD()</code> methods, except that it matches all HTTP methods (verbs).</p> <p>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; <code>loadUser</code> can perform a task, then call <code>next()</code> to continue matching subsequent routes.</p> <pre><code class="language-js">router.all('*', requireAuthentication, loadUser) </code></pre> <p>Or the equivalent:</p> <pre><code class="language-js">router.all('*', requireAuthentication) router.all('*', loadUser) </code></pre> <p>Another example of this is white-listed “global” functionality. Here the example is much like before, but it only restricts paths prefixed with “/api”:</p> <pre><code class="language-js">router.all('/api/*', requireAuthentication) </code></pre> </section> <section> <h3 id="router.METHOD">router.METHOD(path, [callback, ...] callback)</h3> <p>The <code>router.METHOD()</code> 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 <code>router.get()</code>, <code>router.post()</code>, <code>router.put()</code>, and so on.</p> <div class="doc-box doc-info"> <p>The <code>router.get()</code> function is automatically called for the HTTP <code>HEAD</code> method in addition to the <code>GET</code> method if <code>router.head()</code> was not called for the path before <code>router.get()</code>.</p> </div> <p>You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke <code>next('route')</code> 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.</p> <p>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 <em>not</em> considered when performing these matches, for example “GET /” would match the following route, as would “GET /?name=tobi”.</p> <pre><code class="language-js">router.get('/', function (req, res) { res.send('hello world') }) </code></pre> <p>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”.</p> <pre><code class="language-js">router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function (req, res) { var from = req.params[0] var to = req.params[1] || 'HEAD' res.send('commit range ' + from + '..' + to) }) </code></pre> </section> <section> <h3 id="router.param">router.param(name, callback)</h3> <p>Adds callback triggers to route parameters, where <code>name</code> is the name of the parameter and <code>callback</code> is the callback function. Although <code>name</code> is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below).</p> <p>The parameters of the callback function are:</p> <ul> <li><code>req</code>, the request object.</li> <li><code>res</code>, the response object.</li> <li><code>next</code>, indicating the next middleware function.</li> <li>The value of the <code>name</code> parameter.</li> <li>The name of the parameter.</li> </ul> <div class="doc-box doc-info"> <p>Unlike <code>app.param()</code>, <code>router.param()</code> does not accept an array of route parameters.</p> </div> <p>For example, when <code>:user</code> is present in a route path, you may map user loading logic to automatically provide <code>req.user</code> to the route, or perform validations on the parameter input.</p> <pre><code class="language-js">router.param('user', function (req, res, next, id) { // try to get the user details from the User model and attach it to the request object User.find(id, function (err, user) { if (err) { next(err) } else if (user) { req.user = user next() } else { next(new Error('failed to load user')) } }) }) </code></pre> <p>Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on <code>router</code> will be triggered only by route parameters defined on <code>router</code> routes.</p> <p>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.</p> <pre><code class="language-js">router.param('id', function (req, res, next, id) { console.log('CALLED ONLY ONCE') next() }) router.get('/user/:id', function (req, res, next) { console.log('although this matches') next() }) router.get('/user/:id', function (req, res) { console.log('and this matches too') res.end() }) </code></pre> <p>On <code>GET /user/42</code>, the following is printed:</p> <pre><code>CALLED ONLY ONCE although this matches and this matches too </code></pre> <div class="doc-box doc-warn"> <p>The following section describes <code>router.param(callback)</code>, which is deprecated as of v4.11.0.</p> </div> <p>The behavior of the <code>router.param(name, callback)</code> method can be altered entirely by passing only a function to <code>router.param()</code>. This function is a custom implementation of how <code>router.param(name, callback)</code> should behave - it accepts two parameters and must return a middleware.</p> <p>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.</p> <p>The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.</p> <p>In this example, the <code>router.param(name, callback)</code> signature is modified to <code>router.param(name, accessId)</code>. Instead of accepting a name and a callback, <code>router.param()</code> will now accept a name and a number.</p> <pre><code class="language-js">var express = require('express') var app = express() var router = express.Router() // customizing the behavior of router.param() router.param(function (param, option) { return function (req, res, next, val) { if (val === option) { next() } else { res.sendStatus(403) } } }) // using the customized router.param() router.param('id', '1337') // route to trigger the capture router.get('/user/:id', function (req, res) { res.send('OK') }) app.use(router) app.listen(3000, function () { console.log('Ready') }) </code></pre> <p>In this example, the <code>router.param(name, callback)</code> 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.</p> <pre><code class="language-js">router.param(function (param, validator) { return function (req, res, next, val) { if (validator(val)) { next() } else { res.sendStatus(403) } } }) router.param('id', function (candidate) { return !isNaN(parseFloat(candidate)) &amp;&amp; isFinite(candidate) }) </code></pre> </section> <section> <h3 id="router.route">router.route(path)</h3> <p>Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use <code>router.route()</code> to avoid duplicate route naming and thus typing errors.</p> <p>Building on the <code>router.param()</code> example above, the following code shows how to use <code>router.route()</code> to specify various HTTP method handlers.</p> <pre><code class="language-js">var router = express.Router() router.param('user_id', function (req, res, next, id) { // sample user, would actually fetch from DB, etc... req.user = { id: id, name: 'TJ' } next() }) router.route('/users/:user_id') .all(function (req, res, next) { // runs for all HTTP verbs first // think of it as route specific middleware! next() }) .get(function (req, res, next) { res.json(req.user) }) .put(function (req, res, next) { // just an example of maybe updating the user req.user.name = req.params.name // save user ... etc res.json(req.user) }) .post(function (req, res, next) { next(new Error('not implemented')) }) .delete(function (req, res, next) { next(new Error('not implemented')) }) </code></pre> <p>This approach re-uses the single <code>/users/:user_id</code> path and adds handlers for various HTTP methods.</p> <div class="doc-box doc-info"> <p class="doc-info-title"><i class="fa fa-lg fa-info-circle"></i> Note</p> <p>When you use <code>router.route()</code>, middleware ordering is based on when the <em>route</em> 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.</p> </div> </section> <section> <h3 id="router.use">router.use([path], [function, ...] function)</h3> <p>Uses the specified middleware function or functions, with optional mount path <code>path</code>, that defaults to “/”.</p> <p>This method is similar to <a href="#app.use">app.use()</a>. A simple example and use case is described below. See <a href="#app.use">app.use()</a> for more information.</p> <p>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.</p> <pre><code class="language-js">var express = require('express') var app = express() var router = express.Router() // simple logger for this router's requests // all requests to this router will first hit this middleware router.use(function (req, res, next) { console.log('%s %s %s', req.method, req.url, req.path) next() }) // this will only be invoked if the path starts with /bar from the mount point router.use('/bar', function (req, res, next) { // ... maybe some additional /bar logging ... next() }) // always invoked router.use(function (req, res, next) { res.send('Hello World') }) app.use('/foo', router) app.listen(3000) </code></pre> <p>The “mount” path is stripped and is <em>not</em> 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.</p> <p>The order in which you define middleware with <code>router.use()</code> 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.</p> <pre><code class="language-js">var logger = require('morgan') var path = require('path') router.use(logger()) router.use(express.static(path.join(__dirname, 'public'))) router.use(function (req, res) { res.send('Hello') }) </code></pre> <p>Now suppose you wanted to ignore logging requests for static files, but to continue logging routes and middleware defined after <code>logger()</code>. You would simply move the call to <code>express.static()</code> to the top, before adding the logger middleware:</p> <pre><code class="language-js">router.use(express.static(path.join(__dirname, 'public'))) router.use(logger()) router.use(function (req, res) { res.send('Hello') }) </code></pre> <p>Another example is serving files from multiple directories, giving precedence to “./public” over the others:</p> <pre><code class="language-js">router.use(express.static(path.join(__dirname, 'public'))) router.use(express.static(path.join(__dirname, 'files'))) router.use(express.static(path.join(__dirname, 'uploads'))) </code></pre> <p>The <code>router.use()</code> method also supports named parameters so that your mount points for other routers can benefit from preloading using named parameters.</p> <p><strong>NOTE</strong>: Although these middleware functions are added via a particular router, <em>when</em> 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:</p> <pre><code class="language-js">var authRouter = express.Router() var openRouter = express.Router() authRouter.use(require('./authenticate').basic(usersdb)) authRouter.get('/:user_id/edit', function (req, res, next) { // ... Edit user UI ... }) openRouter.get('/', function (req, res, next) { // ... List users ... }) openRouter.get('/:user_id', function (req, res, next) { // ... View user ... }) app.use('/users', authRouter) app.use('/users', openRouter) </code></pre> <p>Even though the authentication middleware was added via the <code>authRouter</code> it will run on the routes defined by the <code>openRouter</code> as well since both routers were mounted on <code>/users</code>. To avoid this behavior, use different paths for each router.</p> </section> </div> </section> <a id="top" href="#"><img src="/images/arrow.png"></a> <footer> <section id="doc-langs"> Documentation translations provided by StrongLoop/IBM: <a href="/fr/">French</a>, <a href="/de/">German</a>, <a href="/es/">Spanish</a>, <a href="/it/">Italian</a>, <a href="/ja/">Japanese</a>, <a href="/ru/">Russian</a>, <a href="/zh-cn/">Chinese</a>, <a href="/zh-tw/">Traditional Chinese</a>, <a href="/ko/">Korean</a>, <a href="/pt-br/">Portuguese</a>. <br> Community translation available for: <a href="/sk/">Slovak</a>, <a href="/uk/">Ukrainian</a>, <a href="/uz/">Uzbek</a>, <a href="/tr/">Turkish</a>, <a href="/th/">Thai</a> and <a href="/id/">Indonesian</a>. </section> <section id="footer-content"> <div id="footer-copyright"> <a href="https://openjsf.org/"> <img src="https://raw.githubusercontent.com/openjs-foundation/artwork/main/openjs_foundation/openjs_foundation-logo-horizontal-color.svg" alt="OpenJS Foundation" width="125" height="39" class="hidden-dark"/> <img src="https://raw.githubusercontent.com/openjs-foundation/artwork/main/openjs_foundation/openjs_foundation-logo-horizontal-white.svg" alt="OpenJS Foundation" width="125" height="39" class="hidden-light"/> </a> <div id="footer-policy"> <a href="https://terms-of-use.openjsf.org">Terms of Use</a> <a href="https://privacy-policy.openjsf.org">Privacy Policy</a> <a id="coc" href="https://github.com/expressjs/express/blob/master/Code-Of-Conduct.md">Code of Conduct</a> <a href="https://trademark-policy.openjsf.org">Trademark Policy</a> <a id="security" href="https://github.com/expressjs/express/security/policy">Security Policy</a> <a id="license" href="https://github.com/expressjs/express/blob/master/LICENSE">License</a> </div> </div> <div id="footer-links"> <div class="footer-social"> <div> <a href="https://github.com/expressjs/express" aria-label="Go to the repository on GitHub"> <span class="hidden-dark"> <svg viewBox="0 0 256 250" width="20" height="20" fill="#24292f" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid" > <path d="M128.001 0C57.317 0 0 57.307 0 128.001c0 56.554 36.676 104.535 87.535 121.46 6.397 1.185 8.746-2.777 8.746-6.158 0-3.052-.12-13.135-.174-23.83-35.61 7.742-43.124-15.103-43.124-15.103-5.823-14.795-14.213-18.73-14.213-18.73-11.613-7.944.876-7.78.876-7.78 12.853.902 19.621 13.19 19.621 13.19 11.417 19.568 29.945 13.911 37.249 10.64 1.149-8.272 4.466-13.92 8.127-17.116-28.431-3.236-58.318-14.212-58.318-63.258 0-13.975 5-25.394 13.188-34.358-1.329-3.224-5.71-16.242 1.24-33.874 0 0 10.749-3.44 35.21 13.121 10.21-2.836 21.16-4.258 32.038-4.307 10.878.049 21.837 1.47 32.066 4.307 24.431-16.56 35.165-13.12 35.165-13.12 6.967 17.63 2.584 30.65 1.255 33.873 8.207 8.964 13.173 20.383 13.173 34.358 0 49.163-29.944 59.988-58.447 63.157 4.591 3.972 8.682 11.762 8.682 23.704 0 17.126-.148 30.91-.148 35.126 0 3.407 2.304 7.398 8.792 6.14C219.37 232.5 256 184.537 256 128.002 256 57.307 198.691 0 128.001 0Zm-80.06 182.34c-.282.636-1.283.827-2.194.39-.929-.417-1.45-1.284-1.15-1.922.276-.655 1.279-.838 2.205-.399.93.418 1.46 1.293 1.139 1.931Zm6.296 5.618c-.61.566-1.804.303-2.614-.591-.837-.892-.994-2.086-.375-2.66.63-.566 1.787-.301 2.626.591.838.903 1 2.088.363 2.66Zm4.32 7.188c-.785.545-2.067.034-2.86-1.104-.784-1.138-.784-2.503.017-3.05.795-.547 2.058-.055 2.861 1.075.782 1.157.782 2.522-.019 3.08Zm7.304 8.325c-.701.774-2.196.566-3.29-.49-1.119-1.032-1.43-2.496-.726-3.27.71-.776 2.213-.558 3.315.49 1.11 1.03 1.45 2.505.701 3.27Zm9.442 2.81c-.31 1.003-1.75 1.459-3.199 1.033-1.448-.439-2.395-1.613-2.103-2.626.301-1.01 1.747-1.484 3.207-1.028 1.446.436 2.396 1.602 2.095 2.622Zm10.744 1.193c.036 1.055-1.193 1.93-2.715 1.95-1.53.034-2.769-.82-2.786-1.86 0-1.065 1.202-1.932 2.733-1.958 1.522-.03 2.768.818 2.768 1.868Zm10.555-.405c.182 1.03-.875 2.088-2.387 2.37-1.485.271-2.861-.365-3.05-1.386-.184-1.056.893-2.114 2.376-2.387 1.514-.263 2.868.356 3.061 1.403Z" /> </svg> </span> <span class="hidden-light"> <svg viewBox="0 0 256 250" width="20" height="20" fill="#fff" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid" > <path d="M128.001 0C57.317 0 0 57.307 0 128.001c0 56.554 36.676 104.535 87.535 121.46 6.397 1.185 8.746-2.777 8.746-6.158 0-3.052-.12-13.135-.174-23.83-35.61 7.742-43.124-15.103-43.124-15.103-5.823-14.795-14.213-18.73-14.213-18.73-11.613-7.944.876-7.78.876-7.78 12.853.902 19.621 13.19 19.621 13.19 11.417 19.568 29.945 13.911 37.249 10.64 1.149-8.272 4.466-13.92 8.127-17.116-28.431-3.236-58.318-14.212-58.318-63.258 0-13.975 5-25.394 13.188-34.358-1.329-3.224-5.71-16.242 1.24-33.874 0 0 10.749-3.44 35.21 13.121 10.21-2.836 21.16-4.258 32.038-4.307 10.878.049 21.837 1.47 32.066 4.307 24.431-16.56 35.165-13.12 35.165-13.12 6.967 17.63 2.584 30.65 1.255 33.873 8.207 8.964 13.173 20.383 13.173 34.358 0 49.163-29.944 59.988-58.447 63.157 4.591 3.972 8.682 11.762 8.682 23.704 0 17.126-.148 30.91-.148 35.126 0 3.407 2.304 7.398 8.792 6.14C219.37 232.5 256 184.537 256 128.002 256 57.307 198.691 0 128.001 0Zm-80.06 182.34c-.282.636-1.283.827-2.194.39-.929-.417-1.45-1.284-1.15-1.922.276-.655 1.279-.838 2.205-.399.93.418 1.46 1.293 1.139 1.931Zm6.296 5.618c-.61.566-1.804.303-2.614-.591-.837-.892-.994-2.086-.375-2.66.63-.566 1.787-.301 2.626.591.838.903 1 2.088.363 2.66Zm4.32 7.188c-.785.545-2.067.034-2.86-1.104-.784-1.138-.784-2.503.017-3.05.795-.547 2.058-.055 2.861 1.075.782 1.157.782 2.522-.019 3.08Zm7.304 8.325c-.701.774-2.196.566-3.29-.49-1.119-1.032-1.43-2.496-.726-3.27.71-.776 2.213-.558 3.315.49 1.11 1.03 1.45 2.505.701 3.27Zm9.442 2.81c-.31 1.003-1.75 1.459-3.199 1.033-1.448-.439-2.395-1.613-2.103-2.626.301-1.01 1.747-1.484 3.207-1.028 1.446.436 2.396 1.602 2.095 2.622Zm10.744 1.193c.036 1.055-1.193 1.93-2.715 1.95-1.53.034-2.769-.82-2.786-1.86 0-1.065 1.202-1.932 2.733-1.958 1.522-.03 2.768.818 2.768 1.868Zm10.555-.405c.182 1.03-.875 2.088-2.387 2.37-1.485.271-2.861-.365-3.05-1.386-.184-1.056.893-2.114 2.376-2.387 1.514-.263 2.868.356 3.061 1.403Z" /> </svg> </span> </a> </div> <div> <a href="https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g" aria-label="Go to the repository on Youtube"><svg viewBox="0 0 256 180" height="20" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid"><path d="M250.346 28.075A32.18 32.18 0 0 0 227.69 5.418C207.824 0 127.87 0 127.87 0S47.912.164 28.046 5.582A32.18 32.18 0 0 0 5.39 28.24c-6.009 35.298-8.34 89.084.165 122.97a32.18 32.18 0 0 0 22.656 22.657c19.866 5.418 99.822 5.418 99.822 5.418s79.955 0 99.82-5.418a32.18 32.18 0 0 0 22.657-22.657c6.338-35.348 8.291-89.1-.164-123.134Z" fill="red"/><path fill="#FFF" d="m102.421 128.06 66.328-38.418-66.328-38.418z"/></svg></a> </div> <div> <a href="https://x.com/UseExpressJS" aria-label="Go to the repository on X"> <span class="hidden-dark"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" viewBox="0 0 1200 1227"><path fill="#000" d="M714.163 519.284 1160.89 0h-105.86L667.137 450.887 357.328 0H0l468.492 681.821L0 1226.37h105.866l409.625-476.152 327.181 476.152H1200L714.137 519.284h.026ZM569.165 687.828l-47.468-67.894-377.686-540.24h162.604l304.797 435.991 47.468 67.894 396.2 566.721H892.476L569.165 687.854v-.026Z"/></svg> </span> <span class="hidden-light"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" viewBox="0 0 1200 1227"><path fill="#fff" d="M714.163 519.284 1160.89 0h-105.86L667.137 450.887 357.328 0H0l468.492 681.821L0 1226.37h105.866l409.625-476.152 327.181 476.152H1200L714.137 519.284h.026ZM569.165 687.828l-47.468-67.894-377.686-540.24h162.604l304.797 435.991 47.468 67.894 396.2 566.721H892.476L569.165 687.854v-.026Z"/></svg> </span> </a> </div> <div> <a href="https://openjs-foundation.slack.com/archives/C02QB1731FH" aria-label="Go to the repository on Slack"><svg viewBox="0 0 2447.6 2452.5" xmlns="http://www.w3.org/2000/svg" width="20" height="20" > <g clip-rule="evenodd" fill-rule="evenodd"> <path d="m897.4 0c-135.3.1-244.8 109.9-244.7 245.2-.1 135.3 109.5 245.1 244.8 245.2h244.8v-245.1c.1-135.3-109.5-245.1-244.9-245.3.1 0 .1 0 0 0m0 654h-652.6c-135.3.1-244.9 109.9-244.8 245.2-.2 135.3 109.4 245.1 244.7 245.3h652.7c135.3-.1 244.9-109.9 244.8-245.2.1-135.4-109.5-245.2-244.8-245.3z" fill="#36c5f0" /> <path d="m2447.6 899.2c.1-135.3-109.5-245.1-244.8-245.2-135.3.1-244.9 109.9-244.8 245.2v245.3h244.8c135.3-.1 244.9-109.9 244.8-245.3zm-652.7 0v-654c.1-135.2-109.4-245-244.7-245.2-135.3.1-244.9 109.9-244.8 245.2v654c-.2 135.3 109.4 245.1 244.7 245.3 135.3-.1 244.9-109.9 244.8-245.3z" fill="#2eb67d" /> <path d="m1550.1 2452.5c135.3-.1 244.9-109.9 244.8-245.2.1-135.3-109.5-245.1-244.8-245.2h-244.8v245.2c-.1 135.2 109.5 245 244.8 245.2zm0-654.1h652.7c135.3-.1 244.9-109.9 244.8-245.2.2-135.3-109.4-245.1-244.7-245.3h-652.7c-135.3.1-244.9 109.9-244.8 245.2-.1 135.4 109.4 245.2 244.7 245.3z" fill="#ecb22e" /> <path d="m0 1553.2c-.1 135.3 109.5 245.1 244.8 245.2 135.3-.1 244.9-109.9 244.8-245.2v-245.2h-244.8c-135.3.1-244.9 109.9-244.8 245.2zm652.7 0v654c-.2 135.3 109.4 245.1 244.7 245.3 135.3-.1 244.9-109.9 244.8-245.2v-653.9c.2-135.3-109.4-245.1-244.7-245.3-135.4 0-244.9 109.8-244.8 245.1 0 0 0 .1 0 0" fill="#e01e5a" /> </g> </svg> </a> </div> <div> <a href="https://opencollective.com/express" aria-label="Go to the repository on Open Collective"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 64 64" fill-rule="evenodd"><path d="M52.402 31.916c0 4.03-1.17 7.895-3.178 11.087l8.196 8.23c4.014-5.375 6.523-12.094 6.523-19.318s-2.51-13.942-6.523-19.318l-8.196 8.23c2.007 3.192 3.178 6.887 3.178 11.087z" fill="#b8d3f4"/><path d="M32.004 52.41c-11.207 0-20.406-9.24-20.406-20.493s9.2-20.493 20.406-20.493c4.182 0 7.86 1.176 11.04 3.36l8.196-8.23C45.887 2.52 39.197 0 32.004 0 14.44 0 .057 14.278.057 32.084S14.44 64 32.004 64c7.36 0 14.05-2.52 19.403-6.55l-8.196-8.23c-3.178 2.016-7.025 3.192-11.207 3.192z" fill="#3385ff"/></svg></a> </div> </div> <a href="https://www.netlify.com"> <img src="https://www.netlify.com/v3/img/components/netlify-color-accent.svg" alt="Preview Deploys by Netlify" width="80" /> </a> </div> </section> </footer> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js" onload="docsearch({ apiKey: '7164e33055faa6ecddefd9e08fc59f5d', indexName: 'expressjs', inputSelector: '#q', algoliaOptions: { 'facetFilters': ['lang:en'] } })" async></script> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10