我如何禁用一种API路线方法的BodyParser,但可以将其启用?

问题描述 投票:0回答:1
问题指出,我如何禁用一个API路线方法的BodyParser,但可以将其启用?

我的API路线的一部分:

const handler = async (req, res) => { if (req.method === "POST") { ... } else if (req.method === "DELETE") { ... } else { res.status(405).json({ data: null, error: "Method not allowed." }); return; }; }; export const config = { api: { bodyParser: false, }, }; export default handler;

您将在代码块的底部看到Body Parser目前适用于两种方法的代码块的底部。我需要将身体解析器用于删除方法,以便可以访问身体内部的变量集,但是对于邮政方法,它需要禁用它(处理图像上传的多部分表单)。
我考虑过将它们分成两个不同的文件,如下所示:

电流设置:

/api/advard/[advartid]/image/index.jsx

  • 电势设置:

/api/advard/[advartid]/image/post.jsx

/api/advard/[advartid]/image/delete.jsx
  • 尽管这将起作用,但它将偏离我的其余代码,因此我想知道是否有一种更干净的方法可以实现这一目标? (最好不使用其他中间件)
  • thanks

我只是遇到了这个问题,并使用了

stripe的github

的功能来做到这一点。
next.js
1个回答
0
投票
const body = await buffer(req); const bodyAsString = body.toString("utf8"); const jsonOfRequest = JSON.parse(bodyAsString); console.log(jsonOfRequest);

wherebuffer

函数如条纹如下。此功能将数据流到缓冲区时,然后在流完成时将块连接在一起。

const buffer = (req: NextApiRequest) => { return new Promise<Buffer>((resolve, reject) => { const chunks: Uint8Array[] = []; req.on("data", (chunk: Uint8Array) => { chunks.push(chunk); }); req.on("end", () => { resolve(Buffer.concat(chunks)); }); req.on("error", reject); }); };

IT是为Stripe Webhook端点验证过程而设计的,但在这里也可以使用。为了使打字稿效果很好,我确实必须编辑
chunks

chunk

的类型。但是,如果您不使用打字稿,则可以删除所有类型。
    

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.