I currently have my database set up with tables and it is correctly connected to the node server. The problem is that when it executes it stores the values as null or undefined which makes me feel like that I am not correctly sending the data from the form.
Below is my Reactjs component file which contains a form and handle functions
import React, {Component} from 'react';
class RegisterComponent extends React.Component {
constructor() {
super();
this.state = {
username: '',
email:'',
password:'',
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = { username:this.state.username, email:this.state.email , password:this.state.password }
fetch('/api/createAccount', { method: 'POST',
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{ 'Content-Type': 'application/json' } })
.then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<label htmlFor="email">Enter your email</label>
<input id="email" name="email" type="email" />
<label htmlFor="password">Enter a password</label>
<input id="password" name="password" type="text" />
<button>Send data!</button>
</form>
);
}
}
export default RegisterComponent;
Below is the api request script
app.post('/api/createAccount', function(req, res) {
const username = req.body.username;
const password = req.body.password;
const email = req.body.email;
con.query(`INSERT INTO usertest2 SET username = ? , email = ? , password = ? `, [username , email, password] , function(err, result) {
console.log(username);
if (err) throw err;
res.send(' successfully');
});
});
bodyParser()? What gets printed when youconsole.log(req.body.username)?app.use(bodyParser.json())and get rid ofapp.use(bodyParser.urlencoded({ extended: false }));