NextJS前后端交互问题:后端错误信息前端解析失败
问题解决:NextJS前后端API错误信息解析失败
问题根源
后端抛出错误时返回的是纯文本字符串,而前端始终用res.json()解析响应,当响应不是JSON格式时就会触发语法错误:
Unexpected token 'P', "Please del"... is not valid JSON
解决方案
方案1:后端统一返回JSON格式响应
修改后端的catch块,用NextResponse.json()返回结构化的错误信息,确保前端能正常解析:
export async function DELETE( req: Request, { params }: { params: { productId: string } } ) { try { const storeId = '665a238f72ab3f9616e1a1d8'; const product = await prismadb.product.deleteMany({ where: { id: params.productId, }, }); return NextResponse.json(product); } catch (error: any) { // 返回JSON格式的错误对象 return NextResponse.json( { message: 'Please delete all transactions and auctions related with this product to continue' }, { status: 500 } ); } }
方案2:前端处理非JSON响应(兼容现有后端)
如果不想修改后端,前端需要先判断响应状态码,非2xx状态时读取文本而非JSON:
修改前端API调用代码:
import { Product } from "@/types"; const URL = `${process.env.NEXT_PUBLIC_API_URL}/products` const deleteProduct = async (params: string): Promise<Product | { error: string }> => { const url = `${URL}/${params}` const res = await fetch(url, { method: 'DELETE', headers: { "Content-type": "application/json; charset=UTF-8" }, }); if (!res.ok) { // 非成功状态时读取文本错误信息并抛出 const errorText = await res.text(); throw new Error(errorText); } return res.json(); } export default deleteProduct
修改前端删除逻辑,在catch中捕获并处理错误:
const onDelete = async () => { try { setLoading(true); if (!selectedProduct) { toast.error('Unauthorized!') setLoading(false); return; } await deleteProduct(selectedProductId); // 删除成功后跳转(可选) // window.location.replace(`/dashboard/shops/${params.shopId}`) } catch (error: any) { // 显示后端返回的错误信息 toast.error(error.message); console.log(error.message); } finally { setLoading(false); } };
关键说明
- 前后端交互时,**统一使用JSON格式传递数据(包括错误信息)**是最佳实践,能从根源避免格式不匹配的解析错误。
- 前端调用
fetch时,res.ok会在状态码处于200-299区间时返回true,非成功状态下需要单独处理响应内容。
内容的提问来源于stack exchange,提问作者Being47
相关产品推荐
相关产品推荐

