Pavel Chukhnov
Pavel Chukhnov

Reputation: 33

How do I send data from React to Node server and back result to React?

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

Upvotes: 3

Views: 7479

Answers (2)

deeps
deeps

Reputation: 491

One can use axios(as I currently use it) to make XMLHttpRequests from the browser or you can use any other dependecy of your liking to make a ajax call. In your _onChange function you need to write something like below to send the data in post method. For this example you need to import axios in your file before using it.

_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);
    });
}});

Also at the server side, you need to get the data which you sended in post request using ajax call.

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

You can check the count value on server console using console.log

Upvotes: 0

Matthew Herbst
Matthew Herbst

Reputation: 31963

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

Upvotes: 2

Related Questions