Ad

How Do I Send Data From React To Node Server And Back Result To React?

- 1 answer

How may I send data from React to Node server and back result to React? I have form on react, and have some data from form, I want to send this data to node server change this data and return result to react.

React code:

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'));

Node:

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('/', fun';

res.send(html);});

app.post('/', function (req, res) {

var expResult = mathjs.eval(req.body.expression);

var html = 'Result: ' + expResult + '.<br>' +
    '<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="/">Try again.</a>';
res.send(html);});

app.listen(3333);
Ad

Answer

Make an ajax call in your _onChange method. Call setState({...}) inside the success callback based on your server's response.

Ad
source: stackoverflow.com
Ad