响应
res 对象表示当 Express 应用收到 HTTP 请求时所发送的 HTTP 响应。
🌐 The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
在本说明文档中,并且按照惯例,
该对象总是被称为 res(HTTP 请求为 req),但其实际名称由你正在使用的回调函数的参数决定。
🌐 In this documentation and by convention,
the object is always referred to as res (and the HTTP request is req) but its actual name is determined
by the parameters to the callback function in which you’re working.
例如:
🌐 For example:
app.get('/user/:id', (req, res) => { res.send(`user ${req.params.id}`);});import { type Request, type Response } from 'express';
app.get('/user/:id', (req: Request, res: Response) => { res.send(`user ${req.params.id}`);});但你同样可以有:
🌐 But you could just as well have:
app.get('/user/:id', (request, response) => { response.send(`user ${request.params.id}`);});import { type Request, type Response } from 'express';
app.get('/user/:id', (request: Request, response: Response) => { response.send(`user ${request.params.id}`);});res 对象是 Node 自带响应对象的增强版本,并支持所有 内置字段和方法。
🌐 The res object is an enhanced version of Node’s own response object
and supports all built-in fields and methods.
属性
🌐 Properties
res.app
此属性保存对正在使用该中间件的 Express 应用实例的引用。
🌐 This property holds a reference to the instance of the Express application that is using the middleware.
res.app 与请求对象中的 req.app 属性是相同的。
app.get('/', (req, res) => { console.dir(res.app.get('view engine')); console.dir(res.app === req.app); // => true res.send('OK');});import { type Request, type Response } from 'express';
app.get('/', (req: Request, res: Response) => { console.dir(res.app.get('view engine')); console.dir(res.app === req.app); // => true res.send('OK');});res.headersSent
布尔属性,指示应用是否为响应发送了 HTTP 头。
🌐 Boolean property that indicates if the app sent HTTP headers for the response.
app.get('/', (req, res) => { console.log(res.headersSent); // false res.send('OK'); console.log(res.headersSent); // true});import { type Request, type Response } from 'express';
app.get('/', (req: Request, res: Response) => { console.log(res.headersSent); // false res.send('OK'); console.log(res.headersSent); // true});res.locals
使用此属性来设置在通过 res.render 渲染的模板中可访问的变量。\n在 res.locals 上设置的变量在单个请求-响应周期内是可用的,并且不会在请求之间共享。
🌐 Use this property to set variables accessible in templates rendered with res.render.
The variables set on res.locals are available within a single request-response cycle, and will not
be shared between requests.
Warning
locals 对象被视图引擎用于渲染响应。对象的键可能特别敏感,不应包含用户控制的输入,因为这可能影响视图引擎的操作或提供跨站脚本攻击的途径。有关更多注意事项,请查阅所使用视图引擎的文档。
🌐 The locals 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.
为了在请求之间保留用于模板渲染的本地变量,请改用 app.locals。
🌐 In order to keep local variables for use in template rendering between requests, use app.locals instead.
此属性对于向应用内呈现的模板公开请求级信息非常有用,例如请求路径名、已验证的用户、用户设置等。
🌐 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.
app.use((req, res, next) => { // Make `user` and `authenticated` available in templates res.locals.user = req.user; res.locals.authenticated = !req.user.anonymous; next();});import { type Request, type Response, type NextFunction } from 'express';
app.use((req: Request, res: Response, next: NextFunction) => { // Make `user` and `authenticated` available in templates res.locals.user = req.user; res.locals.authenticated = !req.user.anonymous; next();});res.req
该属性保存了与此响应对象相关的请求对象的引用。
🌐 This property holds a reference to the request object that relates to this response object.
app.get('/', (req, res) => { console.dir(res.req === req); // => true res.send('OK');});import { type Request, type Response } from 'express';
app.get('/', (req: Request, res: Response) => { console.dir(res.req === req); // => true res.send('OK');});方法
🌐 Methods
res.append()
Arguments
field要附加的 HTTP 响应头名称。
value要附加到该头的值。
将指定的 value 附加到 HTTP 响应头 field。如果该头尚未设置,它将使用指定的值创建该头。value 参数可以是字符串或数组。
🌐 Appends the specified value to the HTTP response header field. If the header is not already set,
it creates the header with the specified value. The value parameter can be a string or an array.
Note
在调用 res.append() 后再调用 res.set() 将会重置先前设置的头部值。
🌐 calling res.set() after res.append() will reset the previously-set header value.
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');res.append('Warning', '199 Miscellaneous warning');res.attachment()
Arguments
filename用于设置 Content-Disposition “filename=” 参数和 Content-Type(根据其扩展名)的文件名。
将 HTTP 响应 Content-Disposition 头字段设置为 “attachment”。如果提供了 filename,则通过 res.type() 根据扩展名设置 Content-Type,并设置 Content-Disposition 的 “filename=” 参数。
🌐 Sets the HTTP response Content-Disposition header field to “attachment”. If a filename is given,
then it sets the Content-Type based on the extension name via res.type(),
and sets the Content-Disposition “filename=” parameter.
res.attachment();// Content-Disposition: attachment
res.attachment('path/to/logo.png');// Content-Disposition: attachment; filename="logo.png"// Content-Type: image/pngres.clearCookie()
Arguments
name要清除的 Cookie 名称。
optionsCookie 选项,应与提供给 res.cookie() 的选项匹配(不包括 expires 和 maxAge)。
通过发送一个 Set-Cookie 头部,将指定的 name cookie 的过期日期设置为过去,从而清除该 cookie。这会告诉客户端该 cookie 已经过期且不再有效。有关可用的 options 的更多信息,请参见 res.cookie()。
🌐 Clears the cookie with the specified name by sending a Set-Cookie header that sets its expiration date in the past.
This instructs the client that the cookie has expired and is no longer valid. For more information
about available options, see res.cookie().
Caution
expires 和 max-age 选项被完全忽略。
🌐 The expires and max-age options are being ignored completely.
Caution
只有当给定的 options 与提供给 res.cookie() 的值相同,网页浏览器和其他兼容客户端才会清除该 cookie
🌐 Web browsers and other compliant clients will only clear the cookie if the given options is
identical to those given to res.cookie()
res.cookie('name', 'tobi', { path: '/admin' });res.clearCookie('name', { path: '/admin' });res.cookie()
Arguments
namecookie 的名称。
valuecookie 的值;对象将被序列化为 JSON。
optionsSet-Cookie 头的选项。
domainCookie的域名。默认为应用的域名。
encode用于 Cookie 值编码的同步函数。默认为“encodeURIComponent”。
expiresCookie的有效期(GMT)。如果未指定或设置为“0”,则会创建一个会话 Cookie。
httpOnly标记该 cookie 仅允许网页服务器访问。
maxAge方便地将到期时间相对于当前时间(毫秒)设置。
path通往Cookie的路径。默认为“/”。
partitioned表示 Cookie 应使用分区存储存储。详情请参见[CHIPS](https://web.nodejs.cn/en-US/docs/Web/Privacy/Guides/Third-party_cookies/Partitioned_cookies)。
priority“优先级”Set-Cookie属性的值。
secure标记 cookie 仅限 HTTPS 使用。
signed指示是否需要签名Cookie。
sameSite“SameSite” Set-Cookie 属性的值。
将 cookie name 设置为 value。value 参数可以是字符串或转换为 JSON 的对象。
🌐 Sets cookie name to value. The value parameter may be a string or object converted to JSON.
Caution
例如:
🌐 For example:
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });res.cookie('remember_me', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });你可以通过多次调用 res.cookie 在一次响应中设置多个 cookie,例如:
🌐 You can set multiple cookies in a single response by calling res.cookie multiple times, for example:
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');encode 选项允许你选择用于 Cookie 值编码的函数。不支持异步函数。
🌐 The encode option allows you to choose the function used for cookie value encoding.
Does not support asynchronous functions.
示例用例:你需要为组织中的另一个站点设置全域 cookie。该站点(不在你的管理控制下)不使用 URI 编码的 cookie 值。
🌐 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.
// Default encodingres.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 encodingres.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=/;'maxAge 选项是一个便捷选项,用于相对于当前时间(以毫秒为单位)设置 “expires”。
以下内容等同于上面的第二个示例。
🌐 The maxAge option is a convenience option for setting “expires” relative to the current time in milliseconds.
The following is equivalent to the second example above.
res.cookie('remember_me', '1', { maxAge: 900000, httpOnly: true });你可以将一个对象作为 value 参数传递;然后它会被序列化为 JSON,并由 bodyParser() 中间件解析。
🌐 You can pass an object as the value parameter; it is then serialized as JSON and parsed by bodyParser() middleware.
res.cookie('cart', { items: [1, 2, 3] });res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });在使用 cookie-parser 中间件时,这个方法也支持签名 cookie。只需包含设置为 true 的 signed 选项。然后,res.cookie() 将使用传递给 cookieParser(secret) 的密钥对值进行签名。
🌐 When using cookie-parser middleware, this method also
supports signed cookies. Simply include the signed option set to true.
Then, res.cookie() will use the secret passed to cookieParser(secret) to sign the value.
res.cookie('name', 'tobi', { signed: true });稍后,你可以通过 req.signedCookies 对象访问此值。
🌐 Later, you may access this value through the req.signedCookies object.
res.download()
Arguments
path要传输的文件路径。如果是相对路径,则相对于当前工作目录或 root 选项解析。
filenameContent-Disposition 的 “filename=” 参数的文件名;会覆盖从 path 得到的名称。
options转发给 res.sendFile() 的选项。
maxAge以毫秒为单位设置 Cache-Control 头的 max-age 属性,或使用 ms 格式 的字符串。
root用于相对文件名的根目录。
lastModified将 Last-Modified 头设置为操作系统中文件的最后修改日期。设置 false 可禁用此功能。
headers包含随文件提供的 HTTP 头的对象。
dotfiles用于处理点文件的选项。可能的值为 "allow"、"deny" 和 "ignore"。
acceptRanges启用或禁用接受范围请求。
cacheControl启用或禁用设置 Cache-Control 响应头。
immutable启用或禁用 Cache-Control 响应头中的 immutable 指令。启用时,应同时指定 maxAge 选项以启用缓存。
fn传输完成或发生错误时调用的回调 fn(err)。
将位于 path 的文件作为“附件”传输。通常,浏览器会提示用户下载。
默认情况下,Content-Disposition 头的 “filename=” 参数由 path 参数派生,但可以通过 filename 参数覆盖。
如果 path 是相对路径,则它将基于进程的当前工作目录,或者如果提供了 root 选项,则基于该选项。
🌐 Transfers the file at path as an “attachment”. Typically, browsers will prompt the user for download.
By default, the Content-Disposition header “filename=” parameter is derived from the path argument, but can be overridden with the filename parameter.
If path is relative, then it will be based on the current working directory of the process or
the root option, if provided.
Warning
此 API 提供对正在运行的文件系统数据的访问。请确保 (a) 如果 path 参数包含用户输入,其构造方式是安全的,或者 (b) 将 root 选项设置为目录的绝对路径以限制访问范围。
🌐 This API provides access to data on the running file system. Ensure that either (a) the way in
which the path argument was constructed is secure if it contains user input or (b) set the root
option to the absolute path of a directory to contain access within.
当提供 root 选项时,Express 将验证作为 path 提供的相对路径是否会在给定的 root 选项内解析。
🌐 When the root option is provided, Express will validate that the relative path provided as
path will resolve within the given root option.
当传输完成或发生错误时,该方法会调用回调函数 fn(err)。如果指定了回调函数并且发生错误,回调函数必须明确处理响应过程,要么通过结束请求-响应周期,要么通过将控制权传递给下一个路由。
🌐 The method invokes the callback function fn(err) 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.
res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.download('/report-12345.pdf', 'report.pdf', (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. }});res.end()
Arguments
data在结束响应之前要写入的数据。
encodingdata 为字符串时的编码。
callback响应完成后调用。
结束响应过程。这个方法实际上来自 Node 核心,具体来说是 http.ServerResponse 的 response.end() 方法。
🌐 Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.
用于快速结束响应而不返回任何数据。如果需要返回数据,请改用诸如 res.send() 和 res.json() 之类的方法。
🌐 Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().
res.end();res.status(404).end();res.format()
Arguments
object一个对象,其键是 MIME 类型(或扩展名),映射到处理函数,可选择包含一个 default 处理函数。
对请求对象上的 Accept HTTP 头进行内容协商(如果存在)。
它使用 req.accepts() 根据按质量值排序的可接受类型来为请求选择处理程序。如果未指定该头,则调用第一个回调。
当没有找到匹配时,服务器会响应 406 “Not Acceptable”,或调用 default 回调。
🌐 Performs content-negotiation on the Accept HTTP header on the request object, when present.
It uses req.accepts() to select a handler for the request, based on the acceptable
types ordered by their quality values. If the header is not specified, the first callback is invoked.
When no match is found, the server responds with 406 “Not Acceptable”, or invokes the default callback.
当选择回调时,会设置 Content-Type 响应头。然而,你可以在回调中使用如 res.set() 或 res.type() 等方法来更改它。
🌐 The Content-Type response header is set when a callback is selected. However, you may alter
this within the callback using methods such as res.set() or res.type().
以下示例将在 Accept 头字段设置为 “application/json” 或 “/json” 时响应 { "message": "hey" }(但是,如果它是 ”/*“,那么响应将是 “hey”)。
🌐 The following example would respond with { "message": "hey" } when the Accept header field is set
to “application/json” or ”*/json” (however, if it is ”*/*”, then the response will be “hey”).
res.format({ 'text/plain'() { res.send('hey'); },
'text/html'() { res.send('<p>hey</p>'); },
'application/json'() { res.send({ message: 'hey' }); },
default() { // log the request and respond with 406 res.status(406).send('Not Acceptable'); },});除了规范化的 MIME 类型外,你还可以使用映射到这些类型的扩展名来实现稍微简洁一些的实现:
🌐 In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:
res.format({ text() { res.send('hey'); },
html() { res.send('<p>hey</p>'); },
json() { res.send({ message: 'hey' }); },});res.get()
Arguments
field要读取的响应头名称(不区分大小写)。
返回由 field 指定的 HTTP 响应头。匹配不区分大小写。
🌐 Returns the HTTP response header specified by field.
The match is case-insensitive.
res.get('Content-Type');// => "text/plain"res.json()
Arguments
body要作为 JSON 发送的值。可以是任何 JSON 类型:对象、数组、字符串、布尔值、数字或 null。
发送一个 JSON 响应。此方法发送一个响应(带有正确的内容类型),该响应是使用 JSON.stringify() 将参数转换为 JSON 字符串。
🌐 Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().
该参数可以是任何 JSON 类型,包括对象、数组、字符串、布尔值、数字或 null,你也可以用它将其他值转换为 JSON。
🌐 The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.
res.json(null);res.json({ user: 'tobi' });res.status(500).json({ error: 'message' });res.jsonp()
Arguments
body作为 JSONP 响应发送的值。可以是任何 JSON 类型。
发送带有 JSONP 支持的 JSON 响应。此方法与 res.json() 相同,但它选择启用 JSONP 回调支持。
🌐 Sends a JSON response with JSONP support. This method is identical to res.json(),
except that it opts-in to JSONP callback support.
res.jsonp(null);// => callback(null)
res.jsonp({ user: 'tobi' });// => callback({ "user": "tobi" })
res.status(500).jsonp({ error: 'message' });// => callback({ "error": "message" })默认情况下,JSONP 回调名称只是 callback。可以通过以下方式覆盖此名称
🌐 By default, the JSONP callback name is simply callback. Override this with the
jsonp 回调名称 设置。
以下是使用相同代码的一些 JSONP 响应示例:
🌐 The following are some examples of JSONP responses using the same code:
// ?callback=foores.jsonp({ user: 'tobi' });// => foo({ "user": "tobi" })
app.set('jsonp callback name', 'cb');
// ?cb=foores.status(500).jsonp({ error: 'message' });// => foo({ "error": "message" })res.links()
Arguments
links一个对象,其属性(例如 next 和 last)用于填充 Link 响应头。 每个值可以是单个 URL 字符串,也可以是 URL 字符串数组,以便为相同的关系发出多个链接。
将作为参数属性提供的 links 连接起来,以填充响应的 Link HTTP 头字段。
🌐 Joins the links provided as properties of the parameter to populate the response’s
Link HTTP header field.
例如,以下调用:
🌐 For example, the following call:
res.links({ next: 'http://api.example.com/users?page=2', last: 'http://api.example.com/users?page=5',});产生以下结果:
🌐 Yields the following results:
Link: <http://api.example.com/users?page=2>; rel="next", <http://api.example.com/users?page=5>; rel="last"res.location()
Arguments
path在 Location 头中设置的 URL。
将响应 Location HTTP 头设置为指定的 path 参数。
🌐 Sets the response Location HTTP header to the specified path parameter.
res.location('/foo/bar');res.location('http://example.com');Warning
在对 URL 进行编码后(如果尚未编码),Express 会将指定的 URL 通过 Location 头部传递给浏览器,而不进行任何验证。
🌐 After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the Location header,
without any validation.
浏览器负责从当前 URL、来源 URL 以及 Location 头中指定的 URL 中获取目标 URL,并相应地重定向用户。
🌐 Browsers take the responsibility of deriving the intended URL from the current URL
or the referring URL, and the URL specified in the Location header; and redirect the user accordingly.
res.redirect()
Arguments
status要使用的 HTTP 状态码。默认值为 302(已找到)。
path要重定向到的 URL。
重定向到由指定的 path 得出的 URL,并使用指定的 status,一个对应于 HTTP 状态码 的正整数。如果未指定,status 默认为 302 "Found"。
🌐 Redirects to the URL derived from the specified path, with specified status, a positive integer
that corresponds to an HTTP status code.
If not specified, status defaults to 302 "Found".
res.redirect('/foo/bar');res.redirect('http://example.com');res.redirect(301, 'http://example.com');res.redirect('../login');重定向可以是一个完全限定的 URL,用于重定向到不同的网站:
🌐 Redirects can be a fully-qualified URL for redirecting to a different site:
res.redirect('https://google.com');重定向可以相对于主机名的根。例如,如果应用在 http://example.com/admin/post/new 上,下面的操作会重定向到 URL http://example.com/admin:
🌐 Redirects can be relative to the root of the host name. For example, if the
application is on http://example.com/admin/post/new, the following
would redirect to the URL http://example.com/admin:
res.redirect('/admin');重定向可以相对于当前的 URL。例如,从 http://example.com/blog/admin/(注意末尾的斜杠),以下操作会重定向到 URL http://example.com/blog/admin/post/new。
🌐 Redirects can be relative to the current URL. For example,
from http://example.com/blog/admin/ (notice the trailing slash), the following
would redirect to the URL http://example.com/blog/admin/post/new.
res.redirect('post/new');从 http://example.com/blog/admin 重定向到 post/new(没有尾部斜杠),将重定向到 http://example.com/blog/post/new。
🌐 Redirecting to post/new from http://example.com/blog/admin (no trailing slash),
will redirect to http://example.com/blog/post/new.
如果你觉得上述行为令人困惑,可以把路径片段看作目录(带斜杠)和文件,这样就会开始理解。
🌐 If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.
路径相对重定向也是可能的。如果你在http://example.com/admin/post/new,以下内容将重定向到http://example.com/admin/post:
🌐 Path-relative redirects are also possible. If you were on
http://example.com/admin/post/new, the following would redirect to
http://example.com/admin/post:
res.redirect('..');另请参见 安全最佳实践:防止开放重定向漏洞。
🌐 See also Security best practices: Prevent open redirect vulnerabilities.
res.render()
Arguments
view要渲染的视图的文件路径(绝对路径或相对于 views 设置的路径)。
locals一个对象,其属性定义视图的本地变量。
callback以 callback(err, html) 调用。提供时,渲染的 HTML 不会自动发送。
渲染一个 view 并将渲染后的 HTML 字符串发送给客户端。可选参数:
🌐 Renders a view and sends the rendered HTML string to the client.
Optional parameters:
locals,一个对象,其属性定义了视图的局部变量。callback,一个回调函数。如果提供,该方法将返回可能的错误和渲染后的字符串,但不会执行自动响应。当发生错误时,该方法会在内部调用next(err)。
view 参数是一个字符串,表示要渲染的视图文件的文件路径。这个路径可以是绝对路径,也可以是相对于 views 设置的路径。如果路径不包含文件扩展名,则由 view engine 设置决定文件扩展名。如果路径包含文件扩展名,Express 将加载指定模板引擎的模块(通过 require())并使用加载模块的 __express 函数进行渲染。
🌐 The view 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 views setting. If the path does not contain a file extension, then the view engine 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 require()) and render it using the loaded module’s __express function.
有关更多信息,请参阅 在 Express 中使用模板引擎。
🌐 For more information, see Using template engines with Express.
Warning
view 参数执行文件系统操作,例如从磁盘读取文件和评估 Node.js 模块,因此出于安全原因不应包含来自终端用户的输入。
🌐 The view 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.
Warning
locals 对象被视图引擎用于渲染响应。对象的键可能特别敏感,不应包含用户控制的输入,因为这可能影响视图引擎的操作或提供跨站脚本攻击的途径。有关更多注意事项,请查阅所使用视图引擎的文档。
🌐 The locals 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.
Caution
局部变量 cache 启用视图缓存。将其设置为 true,即可在开发期间缓存视图;在生产环境中默认启用视图缓存。
🌐 The local variable cache enables view caching. Set it to true, to cache the view during
development; view caching is enabled in production by default.
// send the rendered view to the clientres.render('index');
// if a callback is specified, the rendered HTML string has to be sent explicitlyres.render('index', (err, html) => { res.send(html);});
// pass a local variable to the viewres.render('user', { name: 'Tobi' }, (err, html) => { // ...});res.send()
Arguments
body响应体。字符串作为 HTML 发送;对象和数组作为 JSON 发送;缓冲区作为二进制发送。
发送 HTTP 响应。
🌐 Sends the HTTP response.
body 参数可以是一个 Buffer 对象、一个 String、一个对象、Boolean 或 Array。
例如:
🌐 The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.
For example:
res.send(Buffer.from('whoop'));res.send({ some: 'json' });res.send('<p>some html</p>');res.status(404).send('Sorry, we cannot find that!');res.status(500).send({ error: 'something blew up' });此方法为简单的非流式响应执行许多有用的任务:例如,它会自动分配 Content-Length HTTP 响应头字段,并提供自动的 HEAD 和 HTTP 缓存新鲜度支持。
🌐 This method performs many useful tasks for simple non-streaming responses:
For example, it automatically assigns the Content-Length HTTP response header field
and provides automatic HEAD and HTTP cache freshness support.
当参数是一个 Buffer 对象时,该方法会将 Content-Type 响应头字段设置为 “application/octet-stream”,除非之前已定义,如下所示:
🌐 When the parameter is a Buffer object, the method sets the Content-Type
response header field to “application/octet-stream”, unless previously defined as shown below:
res.set('Content-Type', 'text/html');res.send(Buffer.from('<p>some html</p>'));当参数是 String 时,该方法将 Content-Type 设置为 “text/html”
🌐 When the parameter is a String, the method sets the Content-Type to “text/html”:
res.send('<p>some html</p>');当参数是 Array 或 Object 时,Express 会返回 JSON 表示:
🌐 When the parameter is an Array or Object, Express responds with the JSON representation:
res.send({ user: 'tobi' });res.send([1, 2, 3]);res.sendFile()
Arguments
path要传输的文件路径。除非设置了 root 选项,否则必须是绝对路径。
options用于提供文件的选项。
maxAge以毫秒为单位设置 Cache-Control 头的 max-age 属性,或使用 ms 格式 的字符串。
root用于相对文件名的根目录。
lastModified将 Last-Modified 头设置为操作系统中文件的最后修改日期。设置 false 可禁用此功能。
headers包含随文件提供的 HTTP 头的对象。
dotfiles用于处理点文件的选项。可能的值为 "allow"、"deny" 和 "ignore"。
acceptRanges启用或禁用接受范围请求。
cacheControl启用或禁用设置 Cache-Control 响应头。
immutable启用或禁用 Cache-Control 响应头中的 immutable 指令。启用时,应同时指定 maxAge 选项以启用缓存。
fn传输完成或发生错误时调用的回调 fn(err)。
在给定的 path 处传输文件。根据文件名的扩展名设置 Content-Type 响应 HTTP 头字段。除非在选项对象中设置了 root 选项,否则 path 必须是文件的绝对路径。
🌐 Transfers the file at the given path. Sets the Content-Type response HTTP header field
based on the filename’s extension. Unless the root option is set in
the options object, path must be an absolute path to the file.
Warning
此 API 提供对正在运行的文件系统数据的访问。请确保 (a) 如果 path 参数包含用户输入,其构造为绝对路径的方式是安全的,或者 (b) 将 root 选项设置为目录的绝对路径,以限制访问范围。
🌐 This API provides access to data on the running file system. Ensure that either (a) the way in
which the path argument was constructed into an absolute path is secure if it contains user
input or (b) set the root option to the absolute path of a directory to contain access within.
当提供 root 选项时,允许 path 参数为相对路径,包括包含 .. 的路径。Express 将验证作为 path 提供的相对路径是否将在给定的 root 选项中解析。
🌐 When the root option is provided, the path argument is allowed to be a relative path,
including containing ... Express will validate that the relative path provided as path will
resolve within the given root option.
当传输完成或发生错误时,该方法会调用回调函数 fn(err)。如果指定了回调函数并且发生错误,回调函数必须明确处理响应过程,要么通过结束请求-响应周期,要么通过将控制权传递给下一个路由。
🌐 The method invokes the callback function fn(err) 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.
这是一个使用 res.sendFile 及其所有参数的示例。
🌐 Here is an example of using res.sendFile with all its arguments.
app.get('/file/:name', (req, res, next) => { const options = { root: path.join(__dirname, 'public'), dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true, }, };
const fileName = req.params.name; res.sendFile(fileName, options, (err) => { if (err) { next(err); } else { console.log('Sent:', fileName); } });});import { type Request, type Response, type NextFunction } from 'express';
app.get('/file/:name', (req: Request, res: Response, next: NextFunction) => { const options = { root: path.join(__dirname, 'public'), dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true, }, };
const fileName = req.params.name; res.sendFile(fileName, options, (err) => { if (err) { next(err); } else { console.log('Sent:', fileName); } });});以下示例说明了如何使用 res.sendFile 提供精细化的文件服务支持:
🌐 The following example illustrates using
res.sendFile to provide fine-grained support for serving files:
app.get('/user/:uid/photos/:file', (req, res) => { const uid = req.params.uid; const file = req.params.file;
req.user.mayViewFilesFrom(uid, (yes) => { if (yes) { res.sendFile(`/uploads/${uid}/${file}`); } else { res.status(403).send("Sorry! You can't see that."); } });});import { type Request, type Response } from 'express';
app.get('/user/:uid/photos/:file', (req: Request, res: Response) => { const uid = req.params.uid; const file = req.params.file;
req.user.mayViewFilesFrom(uid, (yes) => { if (yes) { res.sendFile(`/uploads/${uid}/${file}`); } else { res.status(403).send("Sorry! You can't see that."); } });});欲了解更多信息,或如果你有问题或顾虑,请参阅 发送。
🌐 For more information, or if you have issues or concerns, see send.
res.sendStatus()
Arguments
statusCode要设置的 HTTP 状态码;其注册的状态消息将成为响应正文。
将响应的 HTTP 状态码设置为 statusCode,并将已注册的状态消息作为文本响应主体发送。如果指定了未知的状态码,响应主体将仅为代码数字。
🌐 Sets the response HTTP status code to statusCode 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.
res.sendStatus(404);Caution
在某些版本的 Node.js 中,当 res.statusCode 设置为无效的 HTTP 状态码(超出 100 到 599 的范围)时,会抛出异常。请查阅所使用的 Node.js 版本的 HTTP 服务器文档。
🌐 Some versions of Node.js will throw when res.statusCode is set to an invalid HTTP status code
(outside of the range 100 to 599). Consult the HTTP server documentation for the Node.js
version being used.
res.set()
Arguments
field头部名称,或者是一组头部名称/值对象,用于一次设置多个头部。
value头部值(当 field 是字符串时)。
将响应的 HTTP 头 field 设置为 value。
要一次设置多个字段,请将对象作为参数传递。
🌐 Sets the response’s HTTP header field to value.
To set multiple fields at once, pass an object as the parameter.
res.set('Content-Type', 'text/plain');
res.set({ 'Content-Type': 'text/plain', 'Content-Length': '123', ETag: '12345',});别名为 res.header(field [, value])。
🌐 Aliased as res.header(field [, value]).
res.status()
Arguments
code响应的 HTTP 状态码。
设置响应的 HTTP 状态。 它是 Node 的 response.statusCode 的可链别名。
🌐 Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.
res.status(403).end();res.status(400).send('Bad Request');res.status(404).sendFile('/absolute/path/to/404.png');res.type()
Arguments
typeMIME 类型,或查找到 MIME 类型的文件扩展名。如果它包含 /,则按原样使用。
将 Content-Type HTTP 头设置为由指定 type 确定的 MIME 类型。如果 type 包含 ”/” 字符,则将 Content-Type 设置为 type 的精确值,否则它被假定为文件扩展名,并使用 mime-types 包的 contentType() 方法查找 MIME 类型。
🌐 Sets the Content-Type HTTP header to the MIME type as determined by the specified type. If type contains the ”/” character, then it sets the Content-Type to the exact value of type, otherwise it is assumed to be a file extension and the MIME type is looked up using the contentType() method of the mime-types package.
res.type('.html'); // => 'text/html'res.type('html'); // => 'text/html'res.type('json'); // => 'application/json'res.type('application/json'); // => 'application/json'res.type('png'); // => image/png:别名为 res.contentType(type)。
🌐 Aliased as res.contentType(type).
res.vary()
Arguments
field要添加到 Vary 响应头的头字段名称。
如果 Vary 响应头中尚未存在该字段,则将其添加。
🌐 Adds the field to the Vary response header, if it is not there already.
res.vary('User-Agent').render('docs');