将数据从React发送到节点服务器并将结果返回到React

时间:2016-01-23 02:18:45

标签: node.js reactjs

如何将数据从React发送到节点服务器并将结果返回到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);

2 个答案:

答案 0 :(得分:1)

使用_onChange方法拨打ajax电话。根据您服务器的响应,在成功回调中调用setState({...})

答案 1 :(得分:0)

可以使用axios(我目前使用它)从浏览器创建XMLHttpRequests,或者您可以使用您喜欢的任何其他依赖来进行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

检查服务器控制台上的计数值
相关问题