🌐 Nodejs.cn

Express 对象

创建一个 Express 应用。express() 函数是由 express 模块导出的顶层函数。

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

index.cjs
const express = require('express');
const app = express();

方法

🌐 Methods

Express 对象具有以下方法,可用于创建中间件函数、路由以及一些内置中间件:

🌐 The Express object has the following methods that can be used to create middleware functions, routers and have some built-in middleware:

express.json()

Arguments

options
Type:Object | undefined

配置 JSON 正文的解析方式;它接受以下属性。

defaultCharset
Type:StringDefault:"utf-8"

Specify the default character set for the JSON content if the charset is not specified in the Content-Type header of the request.

inflate
Type:BooleanDefault:true

Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.

limit
Type:Number | StringDefault:"100kb"

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

reviver
Type:FunctionDefault:null

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

strict
Type:BooleanDefault:true

Enables or disables only accepting arrays and objects; when disabled will accept anything JSON.parse accepts.

type
Type:String | String[] | FunctionDefault:"application/json"

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, type option is passed directly to the type-is library and this can be an extension name (like json), a mime type (like application/json), or a mime type with a wildcard (like */* or */json). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.

verify
Type:FunctionDefault:undefined

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

这是 Express 中的一个内置中间件函数。它解析带有 JSON 数据的传入请求,并基于 body-parser

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

返回仅解析 JSON 的中间件,并且只查看 Content-Type 头与 type 选项匹配的请求。此解析器接受正文的任何 Unicode 编码,并支持自动解压 gzipdeflate 编码。

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

在中间件(即 req.body)之后,或者在没有需要解析的主体、未匹配 Content-Type 或发生错误的情况下,解析的数据会被填充到 request 对象上的新的 body 对象中。

🌐 A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or undefined if there was no body to parse, the Content-Type was not matched, or an error occurred.

Warning

由于 req.body 的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.body.foo.toString() 可能会以多种方式失败,例如 foo 可能不存在或可能不是字符串,而 toString 可能不是函数,而是字符串或其他用户输入。

🌐 As req.body’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, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

index.cjs
const express = require('express');
const app = express();
// parse requests with a Content-Type of application/json
app.use(express.json());
app.post('/profile', (req, res) => {
console.dir(req.body);
res.json(req.body);
});

express.raw()

Arguments

options
Type:Object | undefined

配置请求正文的解析方式;它接受以下属性。

inflate
Type:BooleanDefault:true

Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.

limit
Type:Number | StringDefault:"100kb"

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

type
Type:String | String[] | FunctionDefault:"application/octet-stream"

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, type option is passed directly to the type-is library and this can be an extension name (like bin), a mime type (like application/octet-stream), or a mime type with a wildcard (like */* or application/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.

verify
Type:FunctionDefault:undefined

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

这是 Express 中的内置中间件函数。它将传入的请求有效负载解析为 Buffer,并且基于 body-parser

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

返回用于解析所有请求体为 Buffer 的中间件,并且只查看 Content-Type 头与 type 选项匹配的请求。该解析器接受请求体的任何 Unicode 编码,并支持自动解压 gzipdeflate 编码。

🌐 Returns middleware that parses all bodies as a Buffer and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

在中间件(即 req.body``)之后,或者如果没有要解析的主体、Content-Type未匹配或发生错误,则在request对象上会填充一个包含解析数据的新body Buffer`。

🌐 A new body Buffer containing the parsed data is populated on the request object after the middleware (i.e. req.body), or undefined if there was no body to parse, the Content-Type was not matched, or an error occurred.

Warning

由于 req.body 的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.body.toString() 可能会以多种方式失败,例如堆叠多个解析器,req.body 可能来自不同的解析器。建议在调用缓冲区方法之前测试 req.body 是否为 Buffer

🌐 As req.body’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, req.body.toString() may fail in multiple ways, for example stacking multiple parsers req.body may be from a different parser. Testing that req.body is a Buffer before calling buffer methods is recommended.

index.cjs
const express = require('express');
const app = express();
// parse requests with a Content-Type of application/octet-stream into a Buffer
app.use(express.raw());
app.post('/upload', (req, res) => {
console.dir(Buffer.isBuffer(req.body)); // => true
res.send(`received ${req.body.length} bytes`);
});

express.Router()

Arguments

caseSensitive
Type:BooleanDefault:false

启用大小写敏感。默认情况下禁用,将 /Foo/foo 视为相同。

mergeParams
Type:BooleanDefault:false

保留来自父路由的 req.params 值。如果父路由和子路由有冲突的参数名,以子路由的值为准。

strict
Type:BooleanDefault:false

启用严格路由。默认情况下禁用,路由将 /foo/foo/ 视为相同。

创建一个新的 router 对象。

🌐 Creates a new router object.

const router = express.Router([options]);

你可以像对待应用一样向 router 添加中间件和 HTTP 方法路由(例如 getputpost 等)。

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

欲了解更多信息,请参见 路由

🌐 For more information, see Router.

express.static()

Arguments

root
Type:String

用于提供静态资源的根目录。

options
Type:Object | undefined

配置文件的提供方式;它接受以下属性。另请参见以下示例

dotfiles
Type:StringDefault:"ignore"

确定如何处理点文件(以点“.”开头的文件或目录)。请参见下文的dotfiles

etag
Type:BooleanDefault:true

启用或禁用 etag 生成。

Note

express.static 总是发送弱 ETag。

extensions
Type:String[] | BooleanDefault:false

Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: ['html', 'htm'].

fallthrough
Type:BooleanDefault:true

Let client errors fall-through as unhandled requests, otherwise forward a client error. See fallthrough below.

immutable
Type:BooleanDefault:false

Enable or disable the immutable directive in the Cache-Control response header. If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.

index
Type:String | BooleanDefault:"index.html"

Sends the specified directory index file. Set to false to disable directory indexing.

lastModified
Type:BooleanDefault:true

Set the Last-Modified header to the last modified date of the file on the OS.

maxAge
Type:NumberDefault:0

Set the max-age property of the Cache-Control header in milliseconds or a string in ms format.

redirect
Type:BooleanDefault:true

Redirect to trailing ”/” when the pathname is a directory.

setHeaders
Type:Function

Function for setting HTTP headers to serve with the file. See setHeaders below.

acceptRanges
Type:BooleanDefault:true

Enable or disable accepting ranged requests. Disabling this will not send the Accept-Ranges header and will ignore the contents of the Range request header.

cacheControl
Type:BooleanDefault:true

Enable or disable setting the Cache-Control response header. Disabling this will ignore the immutable and maxAge options.

这是 Express 中的一个内置中间件函数。它用于提供静态文件,并基于 serve-static

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

Note

为了获得最佳效果,使用反向代理 缓存来提高静态资源提供的性能。

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

root 参数指定用于提供静态资源的根目录。
该函数通过将 req.url 与提供的 root 目录结合来确定要提供的文件。
当未找到文件时,它不会发送 404 响应,而是调用 next()
以继续下一个中间件,从而允许堆叠和回退。

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

有关更多信息,请参阅 在 Express 中提供静态文件使用中间件 - 内置中间件

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

dotfiles

此选项的可能取值为:

🌐 Possible values for this option are:

  • “允许” - 不对点文件给予特殊处理。
  • “deny” - 拒绝对某个点文件的请求,回复 403,然后调用 next()
  • “ignore” - 表现得好像该点文件不存在,回复 404,然后调用 next()

fallthrough

当此选项为 true 时,客户端错误,例如错误请求或请求不存在的文件,将导致此中间件仅调用 next() 以触发堆栈中的下一个中间件。 当为 false 时,这些错误(即使是 404)将调用 next(err)

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

将此选项设置为 true,以便你可以将多个物理目录映射到相同的网页地址,或用于路由填充不存在的文件。

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

如果你已经将此中间件挂载在专门用于单个文件系统目录的路径上,请使用 false,这可以通过短路处理 404 来减少开销。该中间件也会响应所有方法。

🌐 Use false 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.

setHeaders

对于此选项,请指定一个用于设置自定义响应头的函数。对头的更改必须同步进行。

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

函数的签名是:

🌐 The signature of the function is:

fn(res, path, stat);

参数:

🌐 Arguments:

  • res响应对象
  • path,正在发送的文件路径。
  • stat,正在发送的文件的 stat 对象。

express.static 示例

🌐 Example of express.static

这是一个使用 express.static 中间件函数并配合详细选项对象的示例:

🌐 Here is an example of using the express.static middleware function with an elaborate options object:

index.cjs
const express = require('express');
const app = express();
const options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders(res, path, stat) {
res.set('x-timestamp', Date.now());
},
};
app.use(express.static('public', options));

express.text()

Arguments

options
Type:Object | undefined

配置文本主体的解析方式;它接受以下属性。

defaultCharset
Type:StringDefault:"utf-8"

Specify the default character set for the text content if the charset is not specified in the Content-Type header of the request.

inflate
Type:BooleanDefault:true

Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.

limit
Type:Number | StringDefault:"100kb"

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

type
Type:String | String[] | FunctionDefault:"text/plain"

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, type option is passed directly to the type-is library and this can be an extension name (like txt), a mime type (like text/plain), or a mime type with a wildcard (like */* or text/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.

verify
Type:FunctionDefault:undefined

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

这是 Express 中的一个内置中间件函数。它将传入的请求负载解析为字符串,并基于 body-parser

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

返回中间件,该中间件将所有请求体解析为字符串,并且只处理 Content-Type 头与 type 选项匹配的请求。此解析器接受请求体的任何 Unicode 编码,并支持自动解压 gzipdeflate 编码。

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

在中间件(即 req.body``)之后,或者如果没有要解析的主体、未匹配 Content-Type,或发生错误,则会在 request对象上填充包含解析数据的新body字符串,或undefined`。

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

Warning

由于 req.body 的形状是基于用户可控的输入,该对象中的所有属性和值都是不可信的,应在信任前进行验证。例如,req.body.trim() 可能会以多种方式失败,例如堆叠多个 req.body 解析器可能来自不同的解析器。建议在调用字符串方法之前测试 req.body 是否为字符串。

🌐 As req.body’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, req.body.trim() may fail in multiple ways, for example stacking multiple parsers req.body may be from a different parser. Testing that req.body is a string before calling string methods is recommended.

index.cjs
const express = require('express');
const app = express();
// parse requests with a Content-Type of text/plain into a string
app.use(express.text());
app.post('/', (req, res) => {
console.dir(typeof req.body); // => 'string'
res.send(req.body);
});

express.urlencoded()

Arguments

options
Type:Object | undefined

配置 URL 编码的请求体的解析方式;它接受以下属性。

extended
Type:BooleanDefault:false

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

inflate
Type:BooleanDefault:true

Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.

limit
Type:Number | StringDefault:"100kb"

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

parameterLimit
Type:NumberDefault:1000

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.

type
Type:String | String[] | FunctionDefault:"application/x-www-form-urlencoded"

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, type option is passed directly to the type-is library and this can be an extension name (like urlencoded), a mime type (like application/x-www-form-urlencoded), or a mime type with a wildcard (like */x-www-form-urlencoded). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.

verify
Type:FunctionDefault:undefined

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

defaultCharset
Type:StringDefault:"utf-8"

The default charset to parse as, if not specified in content-type. Must be either utf-8 or iso-8859-1.

charsetSentinel
Type:BooleanDefault:false

Whether to let the value of the utf8 parameter take precedence as the charset selector. It requires the form to contain a parameter named utf8 with a value of .

interpretNumericEntities
Type:BooleanDefault:false

Whether to decode numeric entities such as ☺ when parsing an iso-8859-1 form.

depth
Type:NumberDefault:32

Configure the maximum depth of the qs library when extended is true. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. It is recommended to keep this value as low as possible.

这是 Express 中的一个内置中间件函数。它解析带有 urlencoded 负载的传入请求,并基于 body-parser

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

返回只解析 urlencoded 请求体的中间件,并且只处理 Content-Type 头与 type 选项匹配的请求。此解析器仅接受请求体的 UTF-8 编码,并支持自动解压 gzipdeflate 编码。

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

在中间件(即 req.body``)之后,或者如果没有要解析的主体、Content-Type未匹配或发生错误,则在request对象上会填充一个包含解析数据的新body对象。该对象将包含键值对,其中值可以是字符串或数组(当extendedfalse时),或者任何类型(当extendedtrue` 时)。

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

Warning

由于 req.body 的形状基于用户控制的输入,因此此对象中的所有属性和值都是不可信的,应在信任之前进行验证。例如,req.body.foo.toString() 可能会以多种方式失败,例如 foo 可能不存在或可能不是字符串,而 toString 可能不是函数,而是字符串或其他用户输入。

🌐 As req.body’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, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

index.cjs
const express = require('express');
const app = express();
// parse requests with a Content-Type of application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
app.post('/profile', (req, res) => {
console.dir(req.body);
res.json(req.body);
});