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

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

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

  1. const handleAuthentication = async () => {
  2. try {
  3. const responseVariable = await axios({
  4. method: 'POST',
  5. url: '/api/auth',
  6. data: {
  7. username: account,
  8. },
  9. })
  10. console.log(responseVariable) //I get here for 200 status, but not 400
  11. } catch (error) {
  12. console.log(error.message)
  13. }
  14. }

后端身份验证处理程序:

  1. import type { NextApiRequest, NextApiResponse } from 'next'
  2. import { sign } from 'jsonwebtoken'
  3. const Auth = async (req: NextApiRequest, res: NextApiResponse) => {
  4. const { username } = req.body
  5. if (!username) {
  6. res.status(400).json({ message: 'Missing username' })
  7. return
  8. }
  9. const token = sign({ username },process.env.TOKEN_SECRET as string)
  10. return res.status(200).json({ token })
  11. }
  12. }
  13. 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),它修复了这个问题。

相关问题