响应

res 对象表示 Express 应用程序在收到 HTTP 请求时发送的 HTTP 响应。

在本文档中,按照惯例,该对象始终称为 res(HTTP 请求为 req),但其实际名称由您正在使用的回调函数的参数确定。

例如:

app.get('/user/:id', (req, res) => {
  res.send(`user ${req.params.id}`)
})

但你也可以拥有:

app.get('/user/:id', (request, response) => {
  response.send(`user ${request.params.id}`)
})

res对象是Node自带响应对象的增强版,支持所有内置字段和方法

res.app

此属性包含对使用中间件的 Express 应用程序实例的引用。

res.app 与请求对象中的 req.app 属性相同。

res.headersSent

指示应用程序是否为响应发送 HTTP 标头的布尔属性。

app.get('/', (req, res) => {
  console.log(res.headersSent) // false
  res.send('OK')
  console.log(res.headersSent) // true
})

res.locals

使用此属性设置在使用 res.render 呈现的模板中可访问的变量。res.locals 上设置的变量在单个请求-响应周期内可用,并且不会在请求之间共享。

为了保留局部变量以用于请求之间的模板渲染,请改用 app.locals

此属性对于向应用程序中呈现的模板公开请求级信息(例如请求路径名称、经过身份验证的用户、用户设置等)很有用。

app.use((req, res, next) => {
  // Make `user` and `authenticated` available in templates
  res.locals.user = req.user
  res.locals.authenticated = !req.user.anonymous
  next()
})

res.req

此属性包含对与此响应对象相关的 请求对象 的引用。

res.append(field [, value])

Express v4.11.0+ 支持 res.append()

将指定的 value 附加到 HTTP 响应标头 field。如果尚未设置标头,则会创建具有指定值的标头。value 参数可以是字符串或数组。

注意:在 res.append() 之后调用 res.set() 会重置之前设置的 header 值。

res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>'])
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly')
res.append('Warning', '199 Miscellaneous warning')

res.attachment([filename])

将 HTTP 响应 Content-Disposition 标头字段设置为 "attachment"。如果给出了 filename,那么它会根据扩展名通过 res.type() 设置 Content-Type,并设置 Content-Disposition "filename=" 参数。

res.attachment()
// Content-Disposition: attachment

res.attachment('path/to/logo.png')
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png

将 cookie name 设置为 valuevalue 参数可以是字符串或转换为 JSON 的对象。

options 参数是一个可以具有以下属性的对象。

属性类型描述
domain字符串cookie 的域名。默认为应用的域名。
encode函数用于 cookie 值编码的同步函数。默认为 encodeURIComponent
expires日期格林威治标准时间 cookie 的到期日期。如果未指定或设置为 0,则创建会话 cookie。
httpOnly布尔值将 cookie 标记为只能由 Web 服务器访问。
maxAge数字方便的选项,用于设置相对于当前时间的到期时间(以毫秒为单位)。
path字符串cookie 的路径。默认为 "/"。
secure布尔值将 cookie 标记为仅与 HTTPS 一起使用。
signed布尔值指示是否应该对 cookie 进行签名。
sameSite布尔值或字符串"SameSite" Set-Cookie 属性的值。更多信息请参见 https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1

res.cookie() 所做的只是使用提供的选项设置 HTTP Set-Cookie 标头。任何未指定的选项默认为 RFC 6265 中规定的值。

例如:

res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true })
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })

encode 选项允许您选择用于 cookie 值编码的函数。不支持异步函数。

示例用例:您需要为组织中的另一个站点设置域范围的 cookie。此其他站点(不受您的管理控制)不使用 URI 编码的 cookie 值。

// 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=/;'

maxAge 选项是一个方便的选项,用于设置 "expires" 相对于当前时间(以毫秒为单位)。以下等效于上面的第二个示例。

res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })

您可以将对象作为 value 参数传递;然后将其序列化为 JSON 并由 bodyParser() 中间件解析。

res.cookie('cart', { items: [1, 2, 3] })
res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 })

使用 cookie-parser 中间件时,此方法还支持签名 cookie。只需将 signed 选项设置为 true。然后 res.cookie() 将使用传递给 cookieParser(secret) 的秘密对值进行签名。

res.cookie('name', 'tobi', { signed: true })

稍后您可以通过 req.signedCookies 对象访问此值。

res.clearCookie(name [, options])

清除 name 指定的 cookie。关于 options 对象的详细信息,请参见 res.cookie()

Web 浏览器和其他兼容的客户端只会在给定的 options 与给定给 res.cookie() 的相同(不包括 expiresmaxAge)时清除 cookie。

res.cookie('name', 'tobi', { path: '/admin' })
res.clearCookie('name', { path: '/admin' })

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

Express v4.16.0 及更高版本支持可选的 options 参数。

path 处的文件作为 "attachment" 传输。通常,浏览器会提示用户下载。默认情况下,Content-Disposition 标头 "filename=" 参数派生自 path 参数,但可以用 filename 参数覆盖。如果 path 是相对的,那么它将基于进程的当前工作目录。

下表提供了有关 options 参数的详细信息。

Express v4.16.0 及更高版本支持可选的 options 参数。

属性描述默认可用性
maxAge设置 Cache-Control 标头的 max-age 属性(以毫秒为单位)或 ms 格式 中的字符串04.16+
lastModifiedLast-Modified 标头设置为操作系统上文件的最后修改日期。设置 false 以禁用它。启用4.16+
headers包含与文件一起服务的 HTTP 标头的对象。标题 Content-Disposition 将被 filename 参数覆盖。4.16+
dotfiles提供点文件的选项。可能的值为 "allow"、"deny"、"ignore"。"ignore"4.16+
acceptRanges启用或禁用接受范围请求。true4.16+
cacheControl启用或禁用设置 Cache-Control 响应标头。true4.16+
immutableCache-Control 响应标头中启用或禁用 immutable 指令。如果启用,还应指定 maxAge 选项以启用缓存。immutable 指令将阻止受支持的客户端在 maxAge 选项的生命周期内发出条件请求以检查文件是否已更改。false4.16+

该方法在传输完成或发生错误时调用回调函数 fn(err)。如果指定了回调函数并且发生错误,则回调函数必须通过结束请求-响应循环或将控制权传递给下一个路由来显式处理响应过程。

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([data] [, encoding])

结束响应过程。这个方法实际上来自 Node 核心,特别是 http.ServerResponse 的 response.end() 方法

用于在没有任何数据的情况下快速结束响应。如果您需要用数据响应,请改用 res.send()res.json() 等方法。

res.end()
res.status(404).end()

res.format(object)

对请求对象的 Accept HTTP 标头(如果存在)执行内容协商。它使用 req.accepts() 根据质量值排序的可接受类型为请求选择处理程序。如果未指定标头,则调用第一个回调。当没有找到匹配时,服务器响应 406 "Not Acceptable",或者调用 default 回调。

选择回调时设置 Content-Type 响应标头。但是,您可以使用 res.set()res.type() 等方法在回调中更改它。

Accept 头字段设置为 "application/json" 或 "*/json" 时,以下示例将响应 { "message": "hey" }(但是如果它是 "*/*",则响应将为 "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 类型之外,您还可以使用映射到这些类型的扩展名来实现稍微不那么冗长的实现:

res.format({
  text () {
    res.send('hey')
  },

  html () {
    res.send('<p>hey</p>')
  },

  json () {
    res.send({ message: 'hey' })
  }
})

res.get(field)

返回 field 指定的 HTTP 响应标头。匹配不区分大小写。

res.get('Content-Type')
// => "text/plain"

res.json([body])

发送 JSON 响应。此方法发送一个响应(具有正确的内容类型),该响应是使用 JSON.stringify() 转换为 JSON 字符串的参数。

参数可以是任何 JSON 类型,包括对象、数组、字符串、布尔值、数字或 null,您也可以使用它来将其他值转换为 JSON。

res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })

res.jsonp([body])

发送带有 JSONP 支持的 JSON 响应。此方法与 res.json() 相同,只是它选择加入 JSONP 回调支持。

res.jsonp(null)
// => callback(null)

res.jsonp({ user: 'tobi' })
// => callback({ "user": "tobi" })

res.status(500).jsonp({ error: 'message' })
// => callback({ "error": "message" })

默认情况下,JSONP 回调名称只是 callback。用 jsonp 回调名称 设置覆盖它。

以下是使用相同代码的 JSONP 响应的一些示例:

// ?callback=foo
res.jsonp({ user: 'tobi' })
// => foo({ "user": "tobi" })

app.set('jsonp callback name', 'cb')

// ?cb=foo
res.status(500).jsonp({ error: 'message' })
// => foo({ "error": "message" })

加入作为参数属性提供的 links 以填充响应的 Link HTTP 标头字段。

例如,以下调用:

res.links({
  next: 'http://api.example.com/users?page=2',
  last: 'http://api.example.com/users?page=5'
})

产生以下结果:

Link: <http://api.example.com/users?page=2>; rel="next",
      <http://api.example.com/users?page=5>; rel="last"

res.location(path)

将响应 Location HTTP 标头设置为指定的 path 参数。

res.location('/foo/bar')
res.location('http://example.com')
res.location('back')

"back" 的 path 值具有特殊含义,它指的是请求的 Referer 标头中指定的 URL。如果未指定 Referer 标头,则它引用 "/"。

在对 URL 进行编码后,如果尚未编码,Express 会将指定的 URL 在 Location 标头中传递给浏览器,而不进行任何验证。

浏览器负责从当前 URL 或引用 URL 以及 Location 标头中指定的 URL 导出预期 URL;并相应地重定向用户。

res.redirect([status,] path)

重定向到从指定 path 派生的 URL,指定 status,一个对应于 HTTP 状态码 的正整数。如果未指定,则 status 默认为 "302 "Found”。

res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')

重定向可以是用于重定向到不同站点的完全限定 URL:

res.redirect('http://google.com')

重定向可以相对于主机名的根目录。例如,如果应用程序位于 http://example.com/admin/post/new 上,则以下内容将重定向到 URL http://example.com/admin

res.redirect('/admin')

重定向可以相对于当前 URL。例如,从 http://example.com/blog/admin/(注意尾部斜杠)开始,以下内容将重定向到 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

如果您发现上述行为令人困惑,请将路径段视为目录(带有尾部斜杠)和文件,这将开始有意义。

路径相关的重定向也是可能的。如果您在 http://example.com/admin/post/new,以下将重定向到 http://example.com/admin/post

res.redirect('..')

back 重定向将请求重定向回 referer,当引用者丢失时默认为 /

res.redirect('back')

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

呈现 view 并将呈现的 HTML 字符串发送到客户端。可选参数:

  • locals,一个对象,其属性定义视图的局部变量。
  • callback,回调函数。如果提供,该方法将返回可能的错误和呈现的字符串,但不执行自动响应。当发生错误时,该方法在内部调用 next(err)

view 参数是一个字符串,它是要渲染的视图文件的文件路径。这可以是绝对路径,也可以是相对于 views 设置的路径。如果路径不包含文件扩展名,则 view engine 设置确定文件扩展名。如果路径确实包含文件扩展名,那么 Express 将加载指定模板引擎的模块(通过 require())并使用加载模块的 __express 函数渲染它。

有关详细信息,请参阅 使用 Express 模板引擎

注意:view 参数执行文件系统操作,例如从磁盘读取文件和评估 Node.js 模块,因此出于安全原因不应包含来自最终用户的输入。

局部变量 cache 启用视图缓存。设置为true,开发时缓存视图;默认情况下,视图缓存在生产中启用。

// 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', (err, html) => {
  res.send(html)
})

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, (err, html) => {
  // ...
})

res.send([body])

发送 HTTP 响应。

body 参数可以是 Buffer 对象、String、对象、BooleanArray。例如:

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 缓存新鲜度支持。

当参数为 Buffer 对象时,该方法将 Content-Type 响应头字段设置为 "application/octet-stream",除非之前定义如下所示:

res.set('Content-Type', 'text/html')
res.send(Buffer.from('<p>some html</p>'))

当参数为 String 时,该方法将 Content-Type 设置为 "text/html":

res.send('<p>some html</p>')

当参数为 ArrayObject 时,Express 以 JSON 表示形式响应:

res.send({ user: 'tobi' })
res.send([1, 2, 3])

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

Express v4.8.0 及更高版本支持 res.sendFile()

在给定的 path 传输文件。根据文件名的扩展名设置 Content-Type 响应 HTTP 标头字段。除非在选项对象中设置了 root 选项,否则 path 必须是文件的绝对路径。

此 API 提供对正在运行的文件系统上的数据的访问。确保 (a) 将 path 参数构造为绝对路径的方式在包含用户输入时是安全的,或者 (b) 将 root 选项设置为目录的绝对路径以包含其中的访问。

当提供 root 选项时,允许 path 参数为相对路径,包括包含 ..。Express 将验证作为 path 提供的相对路径将在给定的 root 选项中解析。

下表提供了有关 options 参数的详细信息。

属性描述默认可用性
maxAge设置 Cache-Control 标头的 max-age 属性(以毫秒为单位)或 ms 格式 中的字符串0
root相对文件名的根目录。
lastModifiedLast-Modified 标头设置为操作系统上文件的最后修改日期。设置 false 以禁用它。启用4.9.0+
headers包含与文件一起服务的 HTTP 标头的对象。
dotfiles提供点文件的选项。可能的值为 "allow"、"deny"、"ignore"。"ignore" 
acceptRanges启用或禁用接受范围请求。true4.14+
cacheControl启用或禁用设置 Cache-Control 响应标头。true4.14+
immutableCache-Control 响应标头中启用或禁用 immutable 指令。如果启用,还应指定 maxAge 选项以启用缓存。immutable 指令将阻止受支持的客户端在 maxAge 选项的生命周期内发出条件请求以检查文件是否已更改。false4.16+

该方法在传输完成或发生错误时调用回调函数 fn(err)。如果指定了回调函数并且发生错误,则回调函数必须通过结束请求-响应循环或将控制权传递给下一个路由来显式处理响应过程。

这是一个使用 res.sendFile 及其所有参数的示例。

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)
    }
  })
})

以下示例说明了使用 res.sendFile 为服务文件提供细粒度支持:

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.")
    }
  })
})

如需更多信息,或者如果您有问题或疑虑,请参阅 send

res.sendStatus(statusCode)

将响应 HTTP 状态代码设置为 statusCode,并将注册的状态消息作为文本响应正文发送。如果指定了未知状态代码,则响应正文将只是代码编号。

res.sendStatus(404)

res.statusCode 设置为无效的 HTTP 状态代码(超出范围 100599)时,某些版本的 Node.js 会抛出异常。请查阅 HTTP 服务器文档以了解所使用的 Node.js 版本。

更多关于 HTTP 状态码

res.set(field [, value])

将响应的 HTTP 标头 field 设置为 value。要一次设置多个字段,请将对象作为参数传递。

res.set('Content-Type', 'text/plain')

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  ETag: '12345'
})

别名为 res.header(field [, value])

res.status(code)

设置响应的 HTTP 状态。它是 Node 的 response.statusCode 的可链接别名。

res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')

res.type(type)

Content-Type HTTP 标头设置为由指定 type 确定的 MIME 类型。如果 type 包含 "/" 字符,则它将 Content-Type 设置为 type 的确切值,否则假定它是文件扩展名并使用 express.static.mime.lookup() 方法在映射中查找 MIME 类型。

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.vary(field)

将该字段添加到 Vary 响应标头(如果尚不存在)。

res.vary('User-Agent').render('docs')