You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextResponse使用疑问:前端无法获取message及statusText合理性咨询

问题解答

第一段代码的错误分析

  • 参数传递错误:NextResponse.json()仅接受2个参数,第一个是JSON响应主体,第二个是配置对象(含status、headers等)。你传入3个参数时,第二个参数{message: 'Data Captured Successfully'}会被直接忽略,第三个参数{ status: 200 }才会被识别为配置项。这就导致前端无法从响应体中找到message字段——因为这个字段根本没被放入返回的JSON数据里。
  • 修正写法:若要同时返回数据和成功提示,需将两者合并为一个对象作为第一个参数传入:
export async function GET() {
  try {
    const posts = await prisma.post.findMany()
    return NextResponse.json(
      { posts, message: 'Data Captured Successfully' },
      { status: 200 }
    )
  } catch (error) {
    return NextResponse.json({ message: 'Get All Posts Error', error }, { status: 500 })
  }
}

第二段代码的问题分析

  • statusText的用途偏差:statusText是HTTP状态码的标准描述文本(比如200对应"OK",404对应"Not Found"),属于响应头的一部分,并非响应体的JSON数据。前端想要通过response.json()获取提示信息时,根本读不到statusText里的内容——只能通过response.statusText单独读取这部分值。
  • 合理性判断:用statusText传递业务提示不符合HTTP规范,它仅用于描述状态码的标准含义。业务相关的提示信息应该放在响应体的JSON结构中,才能让前端方便获取并打印。

推荐解决方案

统一将业务提示信息放入响应体的JSON对象中,前端就能稳定获取并打印:

export async function GET() {
  try {
    const posts = await prisma.post.findMany()
    return NextResponse.json(
      { 
        data: posts,
        success: true,
        message: 'Data Captured Successfully' 
      },
      { status: 200 }
    )
  } catch (error) {
    console.error('GET Error:', error)
    return NextResponse.json(
      { 
        success: false,
        message: 'Get All Posts Error', 
        error: error.message 
      },
      { status: 500 }
    )
  }
}

前端调用示例:

async function fetchPosts() {
  const response = await fetch('/api/posts')
  const result = await response.json()
  console.log(result.message) // 可直接获取提示信息
}

内容的提问来源于stack exchange,提问作者ozudev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 04:16:19