如何在 Fastify 中记录响应正文?正文似乎没有作为响应对象的一部分公开:
const fastify = require('fastify')({
logger: {
serializers: {
res: function (res) {
// No body in req afaik
return { }
}
}
}
})
尝试这个:
const fastify = require('fastify')({
logger: {
serializers: {
res: function (res) {
return {
statusCode: res.statusCode,
payload: res.payload,
}
},
}
}
})
fastify.addHook('onSend', function (_request, reply, payload, next) {
Object.assign(reply.res, { payload });
next();
})
如果您的某些有效负载是对象,并且您希望在它们被序列化之前将它们序列化 - 好吧,序列化 - 您也可以添加preSerialization
钩子:
fastify
.addHook('preSerialization', (_request, reply, payload, next) => {
Object.assign(reply.res, { payload });
next();
})
.addHook('onSend', (_request, reply, payload, next) => {
if (!reply.res.payload) Object.assign(reply.res, { payload });
next();
});
这是一个工作示例。我认为这种用法只需要用于调试,因为如果你有很多请求/秒,你会减慢速度。
我还添加了一个 JSON Schema 验证作为演示:
const fastify = require('fastify')({ logger: true })
fastify.register(async function (fastify, opts) {
fastify.addHook('onSend', function (request, reply, payload, next) {
console.log(payload);
next()
})
fastify.get('/', {
schema: {
response: {
'2xx': { properties: { this: { type: 'string' } } }
}
}
}, async function () {
return { this: 'is', a: 'json' }
})
})
fastify.listen(3000)
你会得到:
{“这是”}