Next.js API路由中如何将req.body作为函数参数传入?POST请求体传参报错排查
解决Next.js API路由中POST请求体传入upload函数的报错问题
从你遇到的错误Unexpected input: cannot convert "object" into ImportCandidate可以明确判断:你调用的upload函数不接受普通JavaScript对象作为参数,它需要的是「ImportCandidate」类型的输入——通常是字符串、Blob、File、或者带有特定结构的可读取流/文件描述对象,而你直接把req.body这个对象传进去,就触发了类型不匹配的错误。
根据upload函数能接受普通字符串正常工作的特点,给你几个针对性的解决方案,你可以根据upload的实际需求选择:
方案1:将请求体转为JSON字符串传入
如果upload函数需要接收JSON格式的字符串数据,直接把req.body序列化为JSON字符串即可:
export default async function handler(req, res) { if (req.method !== "POST") { res.status(405).send({ message: "GET not allowed" }); return; } const data = req.body; try { // 将对象转为JSON字符串 const jsonData = JSON.stringify(data); const { hash, uri } = await upload(jsonData); res.status(200).json({ id: hash, uri: uri }); } catch (err) { res .status(500) .json({ msg: "upload failed", error: err.message }); } }
方案2:将请求体转为FormData对象传入
如果upload函数是用于处理表单类上传(比如需要模拟表单提交),可以把req.body转换为FormData对象:
export default async function handler(req, res) { if (req.method !== "POST") { res.status(405).send({ message: "GET not allowed" }); return; } const data = req.body; try { // 构建FormData对象 const formData = new FormData(); Object.entries(data).forEach(([key, value]) => { formData.append(key, value); }); const { hash, uri } = await upload(formData); res.status(200).json({ id: hash, uri: uri }); } catch (err) { res .status(500) .json({ msg: "upload failed", error: err.message }); } }
方案3:转为URL编码的字符串传入
如果upload需要application/x-www-form-urlencoded格式的字符串,用URLSearchParams转换:
export default async function handler(req, res) { if (req.method !== "POST") { res.status(405).send({ message: "GET not allowed" }); return; } const data = req.body; try { // 转为URL编码字符串 const encodedData = new URLSearchParams(data).toString(); const { hash, uri } = await upload(encodedData); res.status(200).json({ id: hash, uri: uri }); } catch (err) { res .status(500) .json({ msg: "upload failed", error: err.message }); } }
额外建议
最好先查看upload函数的文档或类型定义(如果是TS项目),明确它要求的参数类型——这样能更精准地转换req.body,避免试错。比如如果它需要的是Blob,你也可以把JSON字符串转为Blob再传入:
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' }); const { hash, uri } = await upload(blob);
内容的提问来源于stack exchange,提问作者peso
相关产品推荐
相关产品推荐

