0

I am trying to submit a couple text boxes to my SQL database using React js through a post request, then on the server side I am listening for the post and querying the data to my database. Right now both values are returning "undefined" regardless of what the user inputs into the form, so I think I've screwed up the React side code. This is the code I am using

Server.js:

var express = require('express');
var app = express();
var sql = require("mssql");
const bodyParser = require('body-parser');
app.use(bodyParser.json());

var config = {
    user: 'user',
    password: 'pass',
    server: 'localhost', 
    database: 'Master' 
};


app.post('/', function(req, res) {
    res.set('Access-Control-Allow-Origin', '*');
    const { FirstName, LastName } = req.body;
    let connection = new sql.ConnectionPool(config, function(err) {
        let request = new sql.Request(connection);
        request.query("insert into persons (FirstName, LastName) values ('" + FirstName + "', '" + LastName + "')");
    });
    res.send({ message: 'Success'})
});

app.listen(5000, () => {console.log('Server is running..')});

And here is my react code...

postData.js:

import React, { Component } from 'react';

class postData extends Component {

    constructor() {
        super();
        this.state = { user: {} };
        this.onSubmit = this.handleSubmit.bind(this);
      }

      handleSubmit(e) {
        e.preventDefault();
        var self = this;
        // On submit of the form, send a POST request with the data to the server.
        fetch('http://localhost:5000', { 
            method: 'POST',
            body: {
              FirstName: self.refs.FirstName,
              LastName: self.refs.LastName
            }
          })
          .then(function(response) {
            return response.json()
          }).then(function(body) {
            console.log(body);
          });
      }
      render() {
        return (
          <form onSubmit={this.onSubmit}>
            <input type="text" placeholder="First Name" ref="FirstName"/>
            <input type="text" placeholder="Last Name" ref="LastName"/>
            <input type="submit" />
          </form>
        );
      }
}

export default postData;

Again, I'm pretty sure I've screwed up the code on the React side, but I'm pretty new to all this so I'm not sure where to start troubleshooting. When I console.log the req.body on the server side it just returns {}, so it seems like there isn't any data being sent from the react script.

Thanks!

1
  • So when you console.log on the client side, what are the values being sent? Commented Apr 20, 2019 at 11:48

3 Answers 3

1

Thanks for all the help guys. I incorporated a lot of the recommendations you guys gave, but the final straw was the following in my server.js code

app.use(express.json({
    type: ['application/json', 'text/plain']
  }));

Once I included this change I was able to eliminate the undefined error I was getting

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

Comments

0

Add these lines on fetch request:

fetch('http://localhost:5000', 
    { method: 'POST',
    headers: new Headers({
        "Content-Type":"application/json"
    }),
    body: JSON.stringify({ 
        FirstName: self.refs.FirstName,
         LastName: self.refs.LastName }) 
})

Then in your server

app.post('/', function(req, res) { 
    res.set('Access-Control-Allow-Origin', '*'); 
    const body = JSON.parse(req.body);
    let connection = new sql.ConnectionPool(config, function(err) { 
    let request = new sql.Request(connection);
    request.query("insert into persons (FirstName, LastName) values ('" + body.FirstName + "', '" + body.LastName + "')"); 
    });
     res.send({ message: 'Success'})
 });

Hope this helps.

1 Comment

Thank you sir. Getting an error on the JSON.stringify part "TypeError: Converting circular structure to JSON". Need to restructure the body?
0

To make your code work just replace this part:

body: {
  FirstName: self.refs.FirstName,
  LastName: self.refs.LastName
}

by this:

body: {
  FirstName: self.refs.FirstName.value,
  LastName: self.refs.LastName.value
}

but I would suggest you to do just like @Yousaf did, and use React.createRef(); to create refs to elements in React

1 Comment

Thanks, but still getting undefined for my values. When I console.log the req.body it just returns {}

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.