我的问题是 API 响应在前端的 JSON 响应中返回 SyntaxError。代码一直抛出的错误是
SyntaxError: Unexpected token 'U', "User not c"... is not valid JSON
代码:
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})
})
const responseRegister = await requestRegister.json()
if(responseRegister.status === 400){
return new Response(responseRegister.message, {status: 400})
} else if (responseRegister.status === 200){
return new Response(responseRegister.message, {status: 200})
}
} catch (error) {
return new Response('Something went wrong', {status: 500})
}
}
我尝试将新的 Routes API 更改为旧格式,但这对我也没有影响。目前我不知道该怎么办。我只是希望前端能够很好地阅读响应并选择响应下一步要做什么。
从错误来看,服务器似乎应该返回一个字符串“User not created”。
我还通过尝试在响应中返回一个字符串得到了这个:
return new Response('response from server', { status: 200 })
为我解决的问题是将主体包裹在 JSON.stringify 中,以便它转换为 JSON 字符串:
return new Response(JSON.stringify('response from server'), { status: 200 });
我还建议将错误文本添加到您的 try/catch 中:
return new Response(JSON.stringify(`Something went wrong ${error}`), { status: 500 });