next.js 为什么我不能访问catch块外的res.status(400)响应?

nxowjjhe  于 2023-04-11  发布在  其他
关注(0)|答案(2)|浏览(122)

关于我正在做的NextJS/Typescript网站的两个问题!目前,我有一个来自前端的身份验证函数,然后在后端服务器上处理。正如你在下面的代码中看到的,这个函数返回一个res.status(400)当存在错误和资源状态时(200)当一切正常时。然而,我似乎不能将此状态存储在等待函数结束的responseVariable中。相反,它立即在我的前端控制台上显示一个错误。但是,当状态为200时,这不是真的;在这种情况下,我实际上可以打印出返回的状态。所以我的两个问题是:
1.为什么我不能访问responseVariable,当它是一个状态400响应?
1.我知道我可以捕获错误,而不是查看responseVariable,但我似乎无法访问应该在错误中的“Missing username”消息。如何在JSON中访问自定义消息?编辑:当我尝试记录error.response.message时,我得到错误:“类型”Error“上不存在属性”response“。”
在前端调用的身份验证函数:

const handleAuthentication = async () => {
    try {
      const responseVariable = await axios({
        method: 'POST',
        url: '/api/auth',
        data: {
          username: account,
        },
      })
      console.log(responseVariable) //I get here for 200 status, but not 400
    } catch (error) {
      console.log(error.message)
    }
  }

后端身份验证处理程序:

import type { NextApiRequest, NextApiResponse } from 'next'
import { sign } from 'jsonwebtoken'

const Auth = async (req: NextApiRequest, res: NextApiResponse) => {
   const { username } = req.body

   if (!username) {
     res.status(400).json({ message: 'Missing username' })
     return
   }

   const token = sign({ username },process.env.TOKEN_SECRET as string)

   return res.status(200).json({ token })
  }
}

export default Auth
9rygscc1

9rygscc11#

您必须使用此表单来访问从API返回的消息
error.response.data.message

ymdaylpp

ymdaylpp2#

我也遇到了同样的问题。你在使用sentry/nextjs包吗?
https://github.com/getsentry/sentry-javascript/issues/6670
在版本7.30.0中解决了该问题
我更新到最新的sentry/nextjs版本(7.46.0),它修复了这个问题。

相关问题