API 响应概览
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 对象包含许多提供有关 HTTP 响应信息的属性。
🌐 The res object contains a number of properties that provide information about the HTTP response.
res.charset
分配字符集。默认为 “utf-8”。
🌐 Assign the charset. Defaults to “utf-8”.
res.charset = 'value';res.send('<p>some html</p>');// => Content-Type: text/html; charset=valueres.locals
响应的局部变量作用域限定在请求范围内,因此仅在该请求/响应周期中渲染的视图(如果有)中可用。否则,该 API 与 app.locals 相同。
🌐 Response local variables are scoped to the request, thus only available to the view(s) rendered during that request / response cycle, if any. Otherwise this API is identical to app.locals.
此对象用于暴露请求级别的信息,例如请求路径名、已认证的用户、用户设置等。
🌐 This object is useful for exposing request-level information such as the request pathname, authenticated user, user settings etcetera.
app.use(function (req, res, next) { 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.
方法
🌐 Methods
res 对象包含许多方法,可用于发送响应、设置头信息等。
🌐 The res object contains a number of methods that can be used to send responses, set headers, and more.
res.attachment([filename])
将 Content-Disposition 头字段设置为 “attachment”。如果给定了 filename,则 Content-Type 将根据 res.type() 通过扩展名自动设置,并且 Content-Disposition 的 “filename=” 参数将被设置。
🌐 Sets the Content-Disposition header field to “attachment”. If
a filename is given then the Content-Type will be
automatically set based on the extname via res.type(),
and the Content-Disposition’s “filename=” parameter will be set.
res.attachment();// Content-Disposition: attachment
res.attachment('path/to/logo.png');// Content-Disposition: attachment; filename="logo.png"// Content-Type: image/pngres.clearCookie(name, [选项])
🌐 res.clearCookie(name, [options])
清除 cookie name。path 选项默认为 ”/”。
🌐 Clear cookie name. The path option defaults to ”/“.
res.cookie('name', 'tobi', { path: '/admin' });res.clearCookie('name', { path: '/admin' });res.cookie(名称, 值, [选项])
🌐 res.cookie(name, value, [options])
设置 cookie name 为 value,它可以是字符串或转换为 JSON 的对象。path 选项默认为 ”/”。
🌐 Set cookie name to value, which may be a string or object converted to JSON. The path
option defaults to ”/”.
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });res.cookie('remember_me', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });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 previous example.
res.cookie('remember_me', '1', { maxAge: 900000, httpOnly: true });可以传递一个对象,然后将其序列化为 JSON,该 JSON 会被 bodyParser() 中间件自动解析。
🌐 An object may be passed which is then serialized as JSON, which is
automatically parsed by the bodyParser() middleware.
res.cookie('cart', { items: [1, 2, 3] });res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });通过此方法也支持签名 cookie。只需传递 signed 选项。当给定 res.cookie() 时,将使用传递给 express.cookieParser(secret) 的密钥来签署该值。
🌐 Signed cookies are also supported through this method. Simply
pass the signed option. When given res.cookie()
will use the secret passed to express.cookieParser(secret)
to sign the value.
res.cookie('name', 'tobi', { signed: true });稍后你可以通过 req.signedCookie 对象访问该值。
🌐 Later you may access this value through the req.signedCookie object.
res.download(path, [filename], [fn])
将 path 处的文件作为“附件”传输,通常浏览器会提示用户下载。Content-Disposition 的“filename=”参数,也就是会出现在浏览器对话框中的文件名,默认设置为 path,但是你可以提供一个覆盖值 filename。
🌐 Transfer the file at path as an “attachment”,
typically browsers will prompt the user for download. The
Content-Disposition “filename=” parameter, aka the one
that will appear in the browser dialog is set to path
by default, however you may provide an override filename.
当发生错误或传输完成时,可选的回调 fn 会被调用。此方法使用 res.sendfile() 来传输文件。
🌐 When an error has occurred or transfer is complete the optional
callback fn is invoked. This method uses res.sendfile()
to transfer the file.
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, keep in mind the response may be partially-sent // so check res.headerSent } else { // decrement a download credit etc }});res.format(object)
当请求头的 Accept 字段存在时,对其执行内容协商。此方法使用 req.accepted,一个按质量值排序的可接受类型数组,否则调用第一个回调。当没有匹配时,服务器响应 406 “不可接受”,或调用 default 回调。
🌐 Performs content-negotiation on the request Accept header
field when present. This method uses req.accepted, an array of
acceptable types ordered by their quality values, otherwise the
first callback is invoked. When no match is performed the server
responds with 406 “Not Acceptable”, or invokes the default
callback.
当选择回调时,Content-Type 会为你设置,然而你可以在回调中使用 res.set() 或 res.type() 等更改它。
🌐 The Content-Type is set for you when a callback is selected,
however you may alter this within the callback using res.set()
or res.type() etcetera.
以下示例在 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 ”/*” is given then “hey” will be the response.
res.format({ 'text/plain': function () { res.send('hey'); },
'text/html': function () { res.send('<p>hey</p>'); },
'application/json': function () { res.send({ message: 'hey' }); },});除了标准化的 MIME 类型,你还可以使用映射到这些类型的扩展名,从而提供一个稍微不那么冗长的实现:
🌐 In addition to canonicalized MIME types you may also use extnames mapped to these types, providing a slightly less verbose implementation:
res.format({ text: function () { res.send('hey'); },
html: function () { res.send('<p>hey</p>'); },
json: function () { res.send({ message: 'hey' }); },});res.get(field)
获取不区分大小写的响应头 field。
🌐 Get the case-insensitive response header field.
res.get('Content-Type');// => "text/plain"res.json([状态|正文], [正文])
🌐 res.json([status|body], [body])
发送 JSON 响应。当传入对象或数组时,此方法与 res.send() 相同,然而它可以用于非对象(null、undefined 等)的显式 JSON 转换,尽管从技术上讲这些并不是有效的 JSON。
🌐 Send a JSON response. This method is identical
to res.send() when an object or
array is passed, however it may be used for
explicit JSON conversion of non-objects (null, undefined, etc),
though these are technically not valid JSON.
res.json(null);res.json({ user: 'tobi' });res.json(500, { error: 'message' });res.jsonp([状态|主体], [主体])
🌐 res.jsonp([status|body], [body])
发送带有 JSONP 支持的 JSON 响应。此方法与 res.json() 相同,但选择支持 JSONP 回调。
🌐 Send a JSON response with JSONP support. This method is identical
to res.json() however opts-in to JSONP callback
support.
res.jsonp(null);// => null
res.jsonp({ user: 'tobi' });// => { "user": "tobi" }
res.jsonp(500, { error: 'message' });// => { "error": "message" }默认情况下,JSONP 回调名称仅为 callback,但是你可以通过 jsonp 回调名称 设置来更改它。以下是使用相同代码的一些 JSONP 响应示例:
🌐 By default the JSONP callback name is simply callback,
however you may alter this with the jsonp callback name
setting. 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.jsonp(500, { error: 'message' });// => foo({ "error": "message" })res.links(links)
连接给定的 links 以填充“Link”响应头字段。
🌐 Join the given links to populate the “Link” response header field.
res.links({ next: 'http://api.example.com/users?page=2', last: 'http://api.example.com/users?page=5',});p 得出结果:
🌐 p yields:
Link: <http://api.example.com/users?page=2> rel="next", <http://api.example.com/users?page=5> rel="last"res.location()
设置位置头。
🌐 Set the location header.
res.location('/foo/bar');res.location('foo/bar');res.location('http://example.com');res.location('../login');res.location('back');你可以使用与 res.redirect() 中相同类型的 urls。
🌐 You can use the same kind of urls as in res.redirect().
例如,如果你的应用挂载在 /blog,以下内容将把 location 头设置为 /blog/admin:
🌐 For example, if your application is mounted at /blog,
the following would set the location header to
/blog/admin:
res.location('admin');res.redirect([状态], 网址)
🌐 res.redirect([status], url)
重定向到给定的 url,可选的 status 代码,默认值为 302 “Found”.
🌐 Redirect to the given url with optional status code
defaulting to 302 “Found”.
res.redirect('/foo/bar');res.redirect('http://example.com');res.redirect(301, 'http://example.com');res.redirect('../login');Express 支持几种形式的重定向,第一种是使用完整的 URI 来重定向到不同的网站:
🌐 Express supports a few forms of redirection, first being a fully qualified URI for redirecting to a different site:
res.redirect('https://google.com');第二种形式是路径名相对重定向,例如
如果你在 http://example.com/admin/post/new,
下面的重定向到 /admin 会将你带到 http://example.com/admin:
🌐 The second form is the pathname-relative redirect, for example
if you were on http://example.com/admin/post/new, the
following redirect to /admin would land you at http://example.com/admin:
res.redirect('/admin');下一个重定向是相对于应用的 mount 点的。例如,如果你有一个挂载在 /blog 的博客应用,理想情况下它不应该知道它被挂载的位置,因此原本 /admin/post/new 的重定向会简单地给你 http://example.com/admin/post/new,而以下相对于挂载点的重定向会给你 http://example.com/blog/admin/post/new:
🌐 This next redirect is relative to the mount point of the application. For example
if you have a blog application mounted at /blog, ideally it has no knowledge of
where it was mounted, so where a redirect of /admin/post/new would simply give you
http://example.com/admin/post/new, the following mount-relative redirect would give
you http://example.com/blog/admin/post/new:
res.redirect('admin/post/new');路径名相对重定向也是可能的。如果你在 http://example.com/admin/post/new,以下重定向将把你引导到 http//example.com/admin/post:
🌐 Pathname relative redirects are also possible. If you were
on http://example.com/admin/post/new, the following redirect
would land you at http//example.com/admin/post:
res.redirect('..');最后一个特殊情况是 back 重定向,重定向回 Referer(或 Referrer),在缺失时默认 /。
🌐 The final special-case is a back redirect, redirecting back to
the Referer (or Referrer), defaulting to / when missing.
res.redirect('back');res.render(视图, [本地变量], 回调)
🌐 res.render(view, [locals], callback)
使用回调渲染 view,回调会返回渲染后的字符串。当发生错误时,next(err) 会在内部被调用。当提供回调时,可能的错误和渲染后的字符串都会被传递,同时不会执行自动响应。
🌐 Render a view with a callback responding with
the rendered string. When an error occurs next(err)
is invoked internally. When a callback is provided both the possible error
and rendered string are passed, and no automated response is performed.
res.render('index', function (err, html) { // ...});
res.render('user', { name: 'Tobi' }, function (err, html) { // ...});res.send([body|状态], [body])
🌐 res.send([body|status], [body])
发送回复。
🌐 Send a response.
res.send(Buffer.from('whoop'));res.send({ some: 'json' });res.send('<p>some html</p>');res.send(404, 'Sorry, we cannot find that!');res.send(500, { error: 'something blew up' });res.send(200);这种方法执行大量有用的任务,用于简单的非流式响应,例如自动分配 Content-Length(除非之前已定义)以及提供自动的 HEAD 和 HTTP 缓存有效性支持。
当提供 Buffer 时,Content-Type 会被设置为 “application/octet-stream”,除非之前已按如下所示定义:
🌐 When a Buffer is given
the Content-Type is set 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 a String is given the
Content-Type is set defaulted to “text/html”:
res.send('<p>some html</p>');当提供 Array 或 Object 时,Express 将响应 JSON 表示:
🌐 When an Array or Object is
given Express will respond with the JSON representation:
res.send({ user: 'tobi' });res.send([1, 2, 3]);最后,当提供一个 Number 而没有任何前面提到的主体时,会为你分配一个响应主体字符串。例如,200 将响应文本 “OK”,404 将响应 “Not Found”,依此类推。
🌐 Finally when a Number is given without
any of the previously mentioned bodies, then a response
body string is assigned for you. For example 200 will
respond will the text “OK”, and 404 “Not Found” and so on.
res.send(200);res.send(404);res.send(500);res.sendfile(path, [选项], [回调函数])
🌐 res.sendfile(path, [options], [fn]])
在给定的 path 处传输文件。
🌐 Transfer the file at the given path.
根据文件名的扩展名自动默认设置 Content-Type 响应头字段。当传输完成或发生错误时,将调用回调 fn(err)。
🌐 Automatically defaults the Content-Type response header field based
on the filename’s extension. The callback fn(err) is
invoked when the transfer is complete or when an error occurs.
选项:
🌐 Options:
maxAge以毫秒为单位,默认为 0root相对文件名的根目录
此方法提供了对文件服务的细粒度支持,如以下示例所示:
🌐 This method provides fine-grained support for file serving as illustrated in the following example:
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.send(403, 'Sorry! you cant see that.'); } });});res.set(字段, [值])
🌐 res.set(field, [value])
将头部 field 设置为 value,或者传递一个对象一次设置多个字段。
🌐 Set header field to value, or pass an object to set multiple fields at once.
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(code)
node 的 res.statusCode= 的可链别名。
🌐 Chainable alias of node’s res.statusCode=.
res.status(404).sendfile('path/to/404.png');res.type(type)
将 Content-Type 设置为 type 的 mime 查找值,或者当存在“/”时,Content-Type 会被直接设置为该字面值。
🌐 Sets the Content-Type to the mime lookup of type,
or when ”/” is present the Content-Type is simply set to this
literal value.
res.type('.html');res.type('html');res.type('json');res.type('application/json');res.type('png');p 被别名为 res.contentType(type)。
🌐 p Aliased as res.contentType(type).