Next.js 13 POST请求遇ReadableStream错误及[object Object]响应问题
问题解决:Next.js 13 POST请求写入MongoDB的响应错误
问题根源
- 请求体获取错误:Next.js 13 App Router中的
req是标准Web Request对象,并非Express风格的请求对象,直接访问req.body得到的是ReadableStream,而非解析后的JSON数据。 - 响应构造错误:
Response构造函数要求传入字符串/二进制流,直接传JavaScript对象会被默认转为"[object Object]",导致客户端看到无效响应。 - 错误处理格式错误:catch块中Response的参数顺序错误,且未正确序列化错误信息。
修正后的代码
export async function POST(req) { // 解析请求体:Web Request需要用await req.json()获取JSON数据 const { nombre, apellido, id, age, direc, cell, email, pass, confirmPass } = await req.json(); try { const newUser = new User({ nombre, apellido, id, age, direc, cell, email, pass, confirmPass }); const savedUser = await newUser.save(); console.log(savedUser); // 将响应对象序列化为JSON字符串,同时设置正确的Content-Type return new Response(JSON.stringify({ body: savedUser }), { headers: { 'Content-Type': 'application/json' }, status: 201 }); } catch (error) { // 错误响应同样需要序列化,设置状态码500 return new Response(JSON.stringify({ error: error.message }), { headers: { 'Content-Type': 'application/json' }, status: 500 }); } }
关键修正点说明
- 用
await req.json()替代直接访问req.body,正确解析POST请求的JSON数据 - 返回
Response时,必须用JSON.stringify()将JavaScript对象转为JSON字符串 - 错误处理中,确保响应体是序列化后的JSON,并正确设置状态码和响应头
内容的提问来源于stack exchange,提问作者RareChimera87
相关产品推荐
相关产品推荐

