【问题标题】:Receive JSON content of Fetch API Post call接收 Fetch API Post 调用的 JSON 内容
【发布时间】:2019-05-11 19:29:17
【问题描述】:

我是 React 的新手,我有一个聊天 UI,我试图在其中测试来自服务的 API 调用。 请假设调用本身具有正确的参数,即使不是,我也希望看到错误 JSON 响应,并且我只是在聊天中收到一条空白消息作为对用户消息的响应。 通过 chrome 中的 Postman 应用程序进行的调用,但是当尝试将调用结果分配给 var in react 时,它在尝试通过 UI 聊天发布消息时不显示 JSON 响应值。

这是函数,用户消息传递给该函数,然后通过获取的 API 请求会立即出现答案:

submitMessage(e) {
    e.preventDefault();

    var s = fetch('https://***', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': '****',
        },
        body: JSON.stringify({ inputText: 'hi' })
    });

    this.setState({
        chats: this.state.chats.concat([
            {
                username: "newUser",
                content: <p>{ReactDOM.findDOMNode(this.refs.msg).value}</p>
            },
            {
                username: "responsePlace",
                content: s
            }
        ])
    });
}

【问题讨论】:

  • Fetch 返回一个承诺,你 then 必须对它做点什么。 fetch(...).then(response =&gt; /* do something with response */)
  • 谢谢,我怎样才能通过“reponsePlace”用户的内容字段发送响应?当将 .then(response => response.json()) 添加到 fetch 并保留其余部分时,会出现错误:“Invariant Violation Objects are not valid as a React child (found: [object Promise]). If你的意思是渲染一个孩子的集合,用一个数组来代替。”。那是在将普通文本字符串分配给 var s 时,可以很好地显示消息。
  • 如果你这样做fetch(...).then(r =&gt; r.json()).then(r =&gt; console.log(r)),响应(r)是什么样的?
  • @wdm 谢谢,我确实得到了所需的 JSON。我需要提取名为“message”的字段的值,并将其放在用户名“reponsePlace”的内容字段中。我怎样才能做到这一点 ?我尝试了几件事,但最终出现了错误..
  • 您需要遍历 chats 数组以找到合适的对象。类似的东西:jsfiddle.net/wfqh9r1e

标签: reactjs rest


【解决方案1】:

fetch 是一个 javascript Promise,因此需要使用 then 解决它

fetch(...) .then(response => response.json()) // resolves json content of the response .then(data => console.log(data)) // your actual data as a javascript object .catch(ex => console.log(ex)) // exception handler in case anything goes wrong in the fetch

更多关于 fetch api:fetch api examples

更多关于承诺:Promises

【讨论】:

  • 谢谢,我怎样才能通过“reponsePlace”用户的内容字段发送响应?当将 .then(response => response.json()) 添加到 fetch 并保留其余部分时,会出现错误:“Invariant Violation Objects are not valid as a React child (found: [object Promise]). If你的意思是渲染一个孩子的集合,用一个数组来代替。”。那是在将普通文本字符串分配给 var s 时,可以很好地显示消息。
猜你喜欢
  • 2017-10-01
  • 2018-07-28
  • 2017-12-31
  • 2012-04-02
  • 1970-01-01
  • 2018-09-17
相关资源
最近更新 更多