javascript - 如何从 react 组件进行远程服务器调用?

标签 javascript node.js reactjs

事情是:我有一个小型 react 应用程序和远程服务器(仅知道 url)。另外,我知道一些服务器方法,例如“GET/api/records” - 从服务器获取所有数据。如何通过这种方式进行通信?

我有一个按钮,它启动一个处理程序,我在其中使用 fetch。

getRecords() {
    fetch("http://xxx.xxx.xxx.xxx:3000/api/records/", {method: "GET"})
        .then((response) => console.log(response));
}

通过console.log,我收到一个Response对象。我如何从中获取数据?

最佳答案

从处理程序中,您可以通过响应来补充您的状态。尝试:

getRecords() {
    fetch("http://xxx.xxx.xxx.xxx:3000/api/records/", {method: "GET"})
        .then(response => response.json())
        .then(data => {
             this.setState({
                 yourDataKey: data
             })
        })
}

来自Google documentation:

The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.

因此,第一个 then 会将流对象转换为 json,第二个 then 会将 json 保存在组件状态上。

关于javascript - 如何从 react 组件进行远程服务器调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57074692/

相关文章:

javascript - 分组堆叠 Highcharts 图中整个堆栈的工具提示

javascript - 有没有我可以重载的方法来处理 JavaScript 中未定义的属性?

javascript - Node中的回调困惑和收集数据

javascript - 在插件中使用 nan 接收和返回 Float32Array

javascript - Nodejs 回调与糟糕的工作流程

javascript - 如何在 reducer 中添加一个对象?

JavaScript 使用一个链接打开两个网页

javascript - 我如何在 react native 应用程序中保留数据?

Reactjs,onclick函数是自动触发的

javascript - 将图像作为 Prop 动态传递给子组件