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!