如何访问Fastify请求的原始主体



正如你所想象的,我对Express很熟悉,但这是我第一次使用Fastify。

我想访问Fastify请求的未经修改的主体,以进行webhook的签名验证——也就是说,我想看到请求的原样,未经任何中间件修改。在Express中,这通常通过访问request.rawBody来完成。

如何访问Fastify请求的原始主体

您也可以检查这个社区插件:https://github.com/Eomm/fastify-raw-body

如果您使用的是Typescript&fastify/autoload,将其放入plugins/rawbody.ts:

import fp from "fastify-plugin";
import rawbody, { RawBodyPluginOptions } from "fastify-raw-body";
export default fp<RawBodyPluginOptions>(async (fastify) => {
fastify.register(rawbody, {
field: "rawBody", // change the default request.rawBody property name
global: false, // add the rawBody to every request. **Default true**
encoding: "utf8", // set it to false to set rawBody as a Buffer **Default utf8**
runFirst: true, // get the body before any preParsing hook change/uncompress it. **Default false**
routes: [], // array of routes, **`global`** will be ignored, wildcard routes not supported
});
});

由于global:false,我们需要在特定的处理程序中配置它:

fastify.post<{ Body: any }>(
"/api/stripe_webhook",
{
config: {
// add the rawBody to this route. if false, rawBody will be disabled when global is true
rawBody: true,
},
},
async function (request, reply) {
...

然后,您可以使用request.rawBody访问处理程序中的原始主体

注意:Fastify请求只能有req.body,不能像其他web服务器(例如Express(那样有req.bbody和req.rawBody。这是因为addContentTypeParser()只返回一个修改后的body,它不能向请求添加任何其他内容。

相反,在一个内容类型解析器中,我们添加到一个路由中,我们生成:

  • req.body.parsed(对象,与通常在req.body中的内容相同(
  • req.body.raw(字符串(

有关更多信息,请参阅GitHub和addContentTypeParser((文档。

server.addContentTypeParser(
"application/json",
{ parseAs: "string" },
function (req, body, done) {
try {
var newBody = {
raw: body,
parsed: JSON.parse(body),
};
done(null, newBody);
} catch (error) {
error.statusCode = 400;
done(error, undefined);
}
}
);

GitHub上存在rawBody支持的问题

还有一个模块:"生坯"。要在Fastify中使用此模块:

const rawBody = require('raw-body')
fastify.addContentTypeParser('*', (req, done) => {
rawBody(req, {
length: req.headers['content-length'],
limit: '1mb',
encoding: 'utf8', // Remove if you want a buffer
}, (err, body) => {
if (err) return done(err)
done(null, parse(body))
})
})

我希望我能帮助你,我也是新来的挑剔

最新更新