0

I am beginner use React Js and Node Js, I get a problem, I cannot post my data from React Js to Node Js, I have been looking for the way but failed all, I don't know why.

This is my complete code.

This is my react file 'member.js', run on port 3000 (http://localhost:3000/member).

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Member extends Component {
  constructor() {
    super();
    this.state = { player: {} };
  }

  handleSubmit(e) {
    e.preventDefault();
    fetch('http://localhost:4000/player', {
        mode: 'no-cors',
        method: 'post',
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify({
          number: 123,
          name: "John",
          position: "Andrew"
        })
    }).then(function(response) {
      console.log(response);
    }).catch(function(error) {
      console.log('Request failed', error)
    });    
  }

  render() {
    return (
      <div className="member-page">
        <form>
          <input type="submit" onClick={this.handleSubmit.bind(this)} />
        </form>
      </div>
    )
  }
}
export default Member;

and this is my node file 'player.js', run on port 4000 (http://localhost:4000/player).

var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express(); 

var connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "react_1"
});

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

    res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();

  var player = req.body;
  var query = connection.query('INSERT INTO player VALUES ?', player, function(err, result) {
    // Neat!
  });
  res.end('Success');
});

app.listen(4000, function() {
  console.log('Example app listening on port 4000!');
});

I don't know where I do a mistake, please anyone correct my code either member.js or player.js.

Thank you very much for all the help.

3
  • Correct me if I'm wrong, but I'm suspecting that the problem is that the server is only accepting when CORS is enabled, and in your client your request has no-cors enabled... I'm not an expert at this but I'm trying to help Commented Sep 20, 2017 at 8:14
  • What is the error that you see in the console Commented Sep 20, 2017 at 8:15
  • Don't set text/plain as content type if you're sending JSON data, and make sure that your server is using body-parser to parse the posted data. Commented Sep 20, 2017 at 8:23

3 Answers 3

0
const express = require('express')
var bodyParser = require('body-parser')
const app = express()
var router = express.Router();
router.use( bodyParser.json() );       // to support JSON-encoded bodies
router.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(5000, () => {
  console.log('Example app listening on port 5000!')
})

app.use('/', router);

Try to Configure your node server like this

Sign up to request clarification or add additional context in comments.

1 Comment

I have tried your recommendation, but when I tried 'console.log(req.body)', in console show undefined, what's next. .?
0

I agree with @robertklep. I think problem is in var player = req.body;

Try:

Install body-parser npm package

npm i -S body-parser

Configure body-parser

   var http = require('http');
   var mysql = require('mysql');
   var express = require('express');
   var bodyParser = require('body-parser');
   var app = express(); 

   app.use(bodyParser.json()); // for parsing application/json
   app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

   //enable CORS
   app.use(function(req, res, next) {
     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
     next();
  });

  var connection = mysql.createConnection({
       host: "localhost",
       user: "root",
       password: "",
       database: "react_1"
  });

  app.post('/player', (req, res) => {
       var player = req.body;
       var query = connection.query('INSERT INTO player VALUES ?', player, (error, results, fields) => {
          if (error) throw error;
          // Neat!
       });
      res.send('Success');
    });

  app.listen(4000, function() {
     console.log('Example app listening on port 4000!');
   });

4 Comments

I have tried your recommendation, but when I tried 'console.log(req.body)', in console show undefined, what's next. .?
@JohnAndrew I moved CORS related code outside the /player route and created a express middleware. Moreover, I changed res.end('Success') to res.send('Success') because res.send uses content-type:text/html as Content-Type. Let me know if it works.
Thank yo very much @Md Zahidul Islam
@JohnAndrew I am happy that it help. Would you mind accepting it as answer.
0

First install body-parser using :

npm install body-parser

const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

If you are passing string data then use

app.use(bodyParser.text());

Otherwise if you are passing data as Json then use

app.use(bodyParser.Json());

It should work in your case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.