将数据从React发送到Node服务器,并将结果发送到React

我如何将数据从React发送到Node服务器,然后将结果发送到React。 我对表单有反应,并且有一些数据,我想把这个数据发送到节点服务器,把这个数据改回这个数据并返回结果。

反应代码:

var Exp = React.createClass({ getInitialState: function () { return {count: ""}; }, handleChange: function (event) { this.setState({count: event.target.value}); }, render: function () { return <div> <h1>Count: {this.state.count}</h1> <form method="post"> <input type="text" onChange={this.handleChange}/> <button onClick={this._onChange}>Submit</button> </form> </div>; }, _onChange: function (event) { event.preventDefault(); console.log("count: " + this.state.count); }});React.render(<Exp />, document.getElementById('container')); 

节点:

 var express = require('express'); var mathjs = require('mathjs'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser()); app.get('/', function (req, res) { var html = '<form action="/" method="post">' + '<input type="text" name="expression" />' + '<br>' + '<button type="submit">Submit</button>' + '</form>'; res.send(html);}); app.post('/', function (req, res) { var expResult = mathjs.eval(req.body.expression); var html = 'Result: ' + expResult + '.<br>' + '<a href="/">Try again.</a>'; res.send(html);}); app.listen(3333); 

_onChange方法中调用ajax调用。 根据服务器的响应,在成功callback中调用setState({...})

可以使用axios(正如我目前使用它)从浏览器中创buildXMLHttpRequests,或者您可以使用您喜欢的任何其他依赖项来进行ajax调用。 在你的_onChange函数中,你需要写下类似的东西来发送post方法中的数据。 对于这个例子,你需要在使用它之前在你的文件中导入axios。

 _onChange: function (event) { axios.post("/",{ countValue: this.state.count }).then((response)=> { console.log("Data submitted successfully"); }).catch((error)=> { console.log("got errr while posting data", error); }); }}); 

同样在服务器端,您需要使用ajax调用来获取您在post请求中发送的数据。

 app.post('/', function (req, res) { var countValue = req.body.countValue; console.log("CountValue is", countValue); }); 

您可以使用console.log检查服务器控制台上的计数值