Next.js v13 API Routes前端JSON响应报SyntaxError问题求助
解决Next.js 13 API Routes返回非JSON响应导致的JSON语法错误
问题根源
你遇到的SyntaxError: Unexpected token 'U', "User not c"... is not valid JSON错误,本质是你的API返回了纯文本字符串,但前端调用时用了response.json()尝试将响应解析为JSON格式,纯文本无法被JSON解析器识别,因此触发语法错误。
看你的代码,返回响应时直接传递了字符串:
return new Response(responseRegister.message, {status: 400})
这种方式返回的响应默认Content-Type是text/plain,而非前端期望的application/json。
解决方案
所有API响应都要返回合法的JSON格式,并显式设置Content-Type头,确保前端能正确解析。
修改后的完整代码
import { getEndpoint } from '@/api/endpoints'; import { NextRequest } from 'next/server'; export async function POST(request: NextRequest){ const {username, email, password } = await request.json() try { const requestRegister = await fetch(getEndpoint('api/v1/auth/signup'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({username, email, password}) }) // 先处理上游响应的异常状态,避免解析非JSON响应报错 let responseRegister; if (requestRegister.ok) { responseRegister = await requestRegister.json(); } else { const errorMsg = await requestRegister.text(); return new Response(JSON.stringify({ message: errorMsg }), { status: requestRegister.status, headers: { 'Content-Type': 'application/json' } }); } if(responseRegister.status === 400){ return new Response(JSON.stringify({ message: responseRegister.message }), { status: 400, headers: { 'Content-Type': 'application/json' } }) } else if (responseRegister.status === 200){ return new Response(JSON.stringify({ message: responseRegister.message }), { status: 200, headers: { 'Content-Type': 'application/json' } }) } } catch (error) { return new Response(JSON.stringify({ message: 'Something went wrong' }), { status: 500, headers: { 'Content-Type': 'application/json' } }) } }
关键修改点
- 将响应内容包装为JSON对象:用
JSON.stringify({ message: xxx })把字符串消息转换成JSON结构,确保响应是合法的JSON格式。 - 显式设置Content-Type头:在
Response的配置中添加headers: { 'Content-Type': 'application/json' },明确告诉前端这是JSON响应。 - 增加上游响应的异常处理:先判断
requestRegister.ok,避免上游返回非JSON格式的错误响应时,当前API的JSON解析步骤报错,导致错误被catch块捕获返回500,无法准确传递上游的错误信息。
这样修改后,前端调用API时用response.json()解析就能正常获取到message字段,不会再触发JSON语法错误。
内容的提问来源于stack exchange,提问作者maciek_pl1234
相关产品推荐
相关产品推荐

