【问题标题】:How to I display the response from the network tab to a react component?如何显示网络选项卡对 React 组件的响应?
【发布时间】:2022-11-17 19:25:59
【问题描述】:

我正在处理一个反应表单,如果用户已经在数据库中注册,则表单基本上会返回响应,否则表单会成功提交。

有一个获取 URL 并返回响应的获取函数。

当存在具有邮件 ID 的现有用户时,我确实在网络选项卡中收到以下消息。

我需要在反应组件中的屏幕上显示此消息。

这是获取主体

fetch(URL, {
    method: "POST",
    mode: "no-cors",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
      "Access-Control-Allow-Origin": "*",
    },
    body: formBody,
  })
    .then((response) => console.log(response))
    .catch((err) => console.log(err));

我得到的响应与网络选项卡中的响应相去甚远。也尝试使用json(),但我遇到了某种错误。

需要帮忙。

【问题讨论】:

  • 嗨,你能试试 .catch(function (error) { errorNotify(error?.response) });
  • 你得到什么回应,你能把它贴在这里吗

标签: javascript reactjs json fetch response


【解决方案1】:

首先,您需要使用以下 .then((response) => response.json()) 将响应转换为 JSON。要通过获取 URL 获取响应数据消息,您需要在 .then((data)=> {...}) 函数中调用以下代码 data.msg。如果要打印消息,您有两个选择:

  1. 您可以使用console.log(data.msg)将其记录到控制台
  2. 通过首先将消息存储在这样的变量中来在组件中返回它:let msg = data.msg.then(...) 函数中,然后添加以下代码:
    return (
    <>
    <h1> {msg} </h1>
    ...
    </>
    )
    

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 2015-09-25
    • 2018-09-07
    • 2015-09-28
    • 2013-12-31
    • 2018-08-26
    相关资源
    最近更新 更多