【发布时间】: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