响应对象

Reply 是路由处理函数的第二个参数,它有下面几个方法:

  • .code(statusCode) - 设置状态码。
  • .header(name, value) - 设置响应头。
  • .type(value) - 设置 Content-Type 字段。
  • .redirect([code,] url) - 重定向到特定的地址,code 参数是可选的 (默认为 302)。
  • .serializer(function) - 为有效荷载设置自定义的序列化器。
  • .send(payload) - 向客户端发送荷载,可以是文本、JSON、流或者一个错误对象。
  • .sent - 一个布尔值,用来判断 `send` 函数是否已经被调用。
fastify.get('/', options, function (request, reply) {
  // You code
  reply
    .code(200)
    .header('Content-Type', 'application/json')
    .send({ hello: 'world' })
})

Code

如果没有设置 reply.code,默认 statusCode 是 200。

设置自定义的响应头。
如果没有设置 'Content-Type' 字段,Fastify 猜测你会使用 'application/json', 除非你要发送一个流, 在这种情况下,Fastify会识别并设置 'Content-Type''application/octet-stream'。

注意,如果使用的序列化器不是序列化到 JSON,则必须设置自定义的 Content-Type 头。

Redirect

重定向一个请求到特定的地址,状态码是可选的,默认为 302。

reply.redirect('/home')

Type

设置响应头的 Content-Type字段。
这是 reply.header('Content-Type', 'the/type') 的简写。

reply.type('text/html')

Serializer

Fastify作为一个完整的JSON兼容服务器而诞生,所以可以直接序列化 send() 函数中的有效荷载。如果你设置了输出 schema,那么会使用 fast-json-stringify 作为格式化JSON的工具包,否则使用 fast-safe-stringify

如果想使用自定义的序列化器,比如 msgpack5 或者 protobuf,则可以使用 .serializer() 方法,注意:如果使用自定义的序列化器却不是序列化成JSON,那么必须得设置自定义的 'Content-Type' 头。

reply
  .header('Content-Type', 'application/x-protobuf')
  .serializer(protoBuf.serialize)

看看这里了解序列化是如何完成的。

Send

正如名字的意思, .send() 是用来向客户端发送有效荷载的。

Objects

正如上面所说, 如果你发送了类 JSON 对象并且设置了输出 schema,那么会使用 fast-json-stringify 作为格式化JSON的工具包,否则使用 fast-safe-stringify

fastify.get('/json', options, function (request, reply) {
  reply.send({ hello: 'world' })
})

Promises

发送原生的 promises 和支持开箱即用的 async-await

fastify.get('/promises', options, function (request, reply) {
  const promise = new Promise(...)
  reply
    .code(200)
    .header('Content-Type', 'application/json')
    .send(promise)
})

fastify.get('/async-await', options, async function (request, reply) {
  var res = await new Promise(function (resolve) {
    setTimeout(resolve, 200, { hello: 'world' })
  })
  // note that we are returning the promise without using '.send()'
  return res
})

Streams

也可以发送流,内部使用 pump 来避免文件描述符的泄露。如果你要发送流,并且尚未设置 “Content-Type” 头,则 send 将会以“application/octet-stream” 进行设置。

fastify.get('/streams', function (request, reply) {
  const fs = require('fs')
  const stream = fs.createReadStream('some-file', 'utf8')
  reply.send(stream)
})

Errors

如果你向 send 函数传入一个 Error 对象的实例,Fastify 将自动创建一个结构如下的错误

{
  error: String        // the http error message
  message: String      // the user error message
  statusCode: Number   // the http status code
}

如果你想要扩展错误对象,可以使用 extendServerError

如果你传入错误对象并且设置小于 400 的状态码,Fastify 将会自动的设置成 500。

有效荷载的类型

发送的有效载荷必须是 字符串Buffer,否则发送将在运行时被抛出。

results matching ""

    No results matching ""