使用POST请求将数据从Node服务器发送回React客户端

时间:2019-09-22 06:19:19

标签: node.js reactjs express post

使用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”?

1 个答案:

答案 0 :(得分:0)

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)
}
相关问题