Fastify 中文文档 (v4.28.1)
Request
处理函数的第一个参数是 Request.
Request 是 Fastify 的核心对象,包含了以下字段:
query- 解析后的 querystring,其格式由querystringParser指定。body- 消息主体params- URL 参数headers- header 的 getter 与 setterraw- Node 原生的 HTTP 请求req(不推荐,请使用.raw) - Node 原生的 HTTP 请求server- Fastify 服务器的实例,以当前的封装上下文为作用域。id- 请求 IDlog- 请求的日志实例ip- 请求方的 ip 地址ips- x-forwarder-for header 中保存的请求源 ip 数组,按访问先后排序 (仅当trustProxy开启时有效)hostname- 请求方的主机名 (当trustProxy启用时,从X-Forwarded-Hostheader 中获取)。为了兼容 HTTP/2,当没有相关 header 存在时,将返回:authority。protocol- 请求协议 (https或http)method- 请求方法url- 请求路径routerMethod- 处理请求的路由函数routerPath- 处理请求的路由的匹配模式is404- 当请求被 404 处理时为 true,反之为 falseconnection- 不推荐,请使用socket。请求的底层连接socket- 请求的底层连接context- Fastify 内建的对象。你不应该直接使用或修改它,但可以访问它的下列特殊属性:context.config- 路由的config对象。
Headers
request.headers 返回来访请求的 header 对象。你也可以如下设置自定义的 header:
request.headers = {
'foo': 'bar',
'baz': 'qux'
}
该操作能向请求 header 添加新的值,且该值能通过 request.headers.bar 读取。此外,request.raw.headers 能让你访问标准的请求 header。
fastify.post('/:params', options, function (request, reply) {
console.log(request.body)
console.log(request.query)
console.log(request.params)
console.log(request.headers)
console.log(request.raw)
console.log(request.server)
console.log(request.id)
console.log(request.ip)
console.log(request.ips)
console.log(request.hostname)
console.log(request.protocol)
console.log(request.url)
console.log(request.routerMethod)
console.log(request.routerPath)
request.log.info('some info')
})