正如您想象的那样,我熟悉Express,但这是我第一次使用Fastify。
我想访问Fastify请求的未经修改的主体,以便对web钩子进行签名验证--也就是说,我希望看到请求在传入时不被任何中间件修改。在Express中,这通常是通过访问request.rawBody
完成的。
如何访问Fastify请求的原始主体?
发布于 2022-09-30 02:40:36
您还可以查看这个社区插件:https://github.com/Eomm/fastify-raw-body
如果您使用的是类型记录& fastify/autoload,请将其放到plugins/rawbody.ts. to中:
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
访问处理程序中的原始主体。
发布于 2020-04-18 21:48:59
Note:Fastify请求只能具有req.body --例如,它们不能像其他web服务器那样拥有req.body和req.rawBody (例如,Express)。这是因为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);
}
}
);
发布于 2020-04-09 13:31:22
还有一个模块:“生身”。要在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))
})
})
我希望我帮了你,我也是新来的
https://stackoverflow.com/questions/61122089
复制相似问题