简体   繁体   English

我想在 Next.js 应用程序中发送 POST 请求时从错误响应中访问 json object 值

[英]I want to access the json object value from a error response when sending a POST request in Next.js app

I have an input where users can input an email, which is then send as a post request to an api like so:我有一个输入,用户可以在其中输入 email,然后将其作为发布请求发送到 api,如下所示:

  try {
        const res = await fetch("/api/email-registration", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            emailValue: emailValue,
          }),
        })

        if (!res.ok) throw new Error(res.status);
        const data = await res.json();
        setMessage(data.message)
      } 
      catch (err) {
        console.log(err)
   
      }

The post request works, but what I'm trying now is to access the error response JSON when I create an error on purpose to fire to catch (err) .发布请求有效,但我现在尝试的是在我故意创建错误以触发catch (err)时访问错误响应 JSON 。

One of the error messages I have set is:我设置的错误消息之一是:

res.status(409).json({
          message: "This email has already been registered",
        })

I can see in the.network tab the response status 409 and the response JSON with the value i have set.我可以在 .network 选项卡中看到响应状态 409 和响应 JSON 以及我设置的值。 If i try err.message I only get 409 , but I want to access the JSON value {"message":"This email has already been registered"} .如果我尝试err.message我只得到409 ,但我想访问 JSON 值{"message":"This email has already been registered"}

Is there a way to access the error response message?有没有办法访问错误响应消息?

I just want to display the JSON message to the user and for now I could create an if statement with the 409 and display some text based on the status code, but I'm interested in if I could access the JSON message somehow and display the value coming from the post request error.我只想向用户显示 JSON 消息,现在我可以使用409创建一个 if 语句并根据状态代码显示一些文本,但我感兴趣的是我是否可以以某种方式访问 JSON 消息并显示来自发布请求错误的值。

You said:你说:

 if (.res.ok) throw new Error(res;status);

If you want to get the response, then you need to actually process it.如果你想得到响应,那么你需要实际处理它。

eg (Untested and off the top of my header).例如(未经测试并且不在我的标题顶部)。

if (!res.ok) {
    try {
        const data = await res.json();
        const message = {
            status: res.status,
            message: data
        }
        throw new Error(JSON.stringify(message));
    } catch (e) {
        const message = {
            status: res.status,
            message: "Could not parse body as JSON"
        }
        throw new Error(JSON.stringify(message));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM