Next.js 13 API路由数据未发送且JSON解析报错求助
问题修复方案
核心问题分析
你的代码存在两个关键错误:
- 前端错误组合使用
FormData与JSON.stringify,导致发送的内容并非合法JSON;同时手动设置Content-Type: application/json与FormData的传输格式不兼容。 - 后端错误地对
req.body执行await JSON.parse()——Next.js的API路由会自动解析JSON格式的请求体,req.body已经是解析后的对象,再次解析会触发语法错误。
修复方案一:直接发送JSON(推荐)
这种方式更简洁,适合传递数组这类结构化数据:
前端代码修改
const sendToAPI = () => { fetch("/api/uploadToMongoDB", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ urls: downloadUrls }), // 直接将数组包装为JSON对象发送 }) .then((res) => res.json()) // 记得解析响应的JSON数据 .then((data) => console.log(data)) .catch((e) => console.log(e)); };
后端代码修改
export default async function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method !== 'POST') { res.status(405).json({ message: '仅允许POST请求' }) return } // req.body已被Next.js自动解析为JSON对象,直接使用即可 const { urls } = req.body res.status(200).json({ message: '你提交的数据:', urls }) }
修复方案二:使用FormData(适合上传文件等场景)
如果必须使用FormData,需调整前后端的处理逻辑:
前端代码修改
const sendToAPI = () => { const data = new FormData(); data.append("urls", JSON.stringify(downloadUrls)); fetch("/api/uploadToMongoDB", { method: "POST", // 不要手动设置Content-Type,浏览器会自动添加正确的multipart/form-data请求头 body: data, }) .then((res) => res.json()) .then((data) => console.log(data)) .catch((e) => console.log(e)); };
后端代码修改
Next.js Pages目录的API路由默认不自动解析multipart/form-data格式,需借助formidable库处理:
首先安装依赖:
npm install formidable # 或 yarn add formidable
然后修改API路由:
import formidable from 'formidable' import type { NextApiRequest, NextApiResponse } from 'next' // 禁用Next.js默认的请求体解析 export const config = { api: { bodyParser: false, }, } export default async function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method !== 'POST') { res.status(405).json({ message: '仅允许POST请求' }) return } const form = formidable({}); const [fields] = await form.parse(req); // 解析FormData中的urls字段 const urls = JSON.parse(fields.urls[0]) res.status(200).json({ message: '你提交的数据:', urls }) }
错误原因补充
你遇到的Unexpected token o in JSON at position 1错误,是因为JSON.stringify(data)(data为FormData对象)会生成类似{"_entries":[[...]]}的字符串,后端若按JSON格式解析后,req.body已变成对象,此时再执行JSON.parse(req.body),相当于尝试解析字符串[object Object],自然会触发语法错误。
内容的提问来源于stack exchange,提问作者Captai-N
相关产品推荐
相关产品推荐

