# res.format

对请求对象的 Accept HTTP 标头(如果存在)执行内容协商。

# 概要

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' })
  }
})
Last Updated: 3/22/2023, 7:27:28 PM