【问题标题】:Send data back to React client from Node server with POST request使用 POST 请求将数据从 Node 服务器发送回 React 客户端
【发布时间】:2020-02-11 19:22:20
【问题描述】:

一个使用 React 和 Nodejs 的非常简单的计数器应用程序。在客户端,我有一个计数器组件,它由计数状态和呈现在 UI 上的默认值 0 组成,每次用户按下增量按钮时,它都会向节点服务器触发 POST 请求 API。然后节点服务器将处理请求并用其结果响应客户端。我将如何做到这一点?

客户端(计数器组件)

this.state = {
   count : 0
}

sendAPI() {
   axios.post('http://localhost:3001/increment', this.state.count)...
}

render() {
    <div>
        <button onClick = {this.sendAPI()} type="button">increment</button>
        Counter: {this.state.count}  
    </div>
}

服务器端(快递服务器)

app.post('/increment', function(req,res) {
     res.send(req.body.count + 1)
}

如何将 res.send() 数据返回到客户端的“this.state.count”?

【问题讨论】:

  • 在 axios Ajax 查询中应该有一个“完成”或“回调”或“然后”函数。在那里,您将收到您使用res.send() 发送的数据。我建议您查看 axios 文档。只需在 Google 上搜索axios post,您就会看到很多示例。

标签: node.js reactjs express post


【解决方案1】:

在按钮onClick 中不要调用函数,而是将函数作为引用传递。

state = {
   count : 0
}

sendAPI() {
   axios.post('http://localhost:3001/increment', {count: this.state.count})
       .then(res => {
               const count = res.data;
               this.setState({count: +count})
           );
}

render() {
    <div>
        <button onClick = {this.sendAPI} type="button">increment</button>
        Counter: {this.state.count}  
    </div>
}

服务器端(快递服务器)

app.post('/increment', function(req,res) {
     res.send(+req.body.count + 1)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多