I'm trying to send data to my Flask API to get data into my database, but I keep getting the following error: OPTIONS /createUser HTTP/1.1" 400
Reg.js
import React, { Component } from 'react';
class Reg extends Component {
constructor() {
super();
this.state = {
FirstName: '',
LastName: '',
Email: '',
Password: ''
}
this.Email = this.Email.bind(this);
this.Password = this.Password.bind(this);
this.FirstName = this.FirstName.bind(this);
this.LastName = this.LastName.bind(this);
this.register = this.register.bind(this);
}
Email(event) {
this.setState({ Email: event.target.value })
}
Password(event) {
this.setState({ Password: event.target.value })
}
FirstName(event) {
this.setState({ FirstName: event.target.value })
}
LastName(event) {
this.setState({ LastName: event.target.value })
}
register(event) {
fetch('http://localhost:5000/createUser', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
},
body: JSON.stringify({
"FirstName": this.state.FirstName,
"Password": this.state.Password,
"Email": this.state.Email,
"LastName": this.state.LastName
})
}).then(function(res){
return res.json();
}).then(function(data){
console.log(data);
}).catch((error) => {
console.log(error);
});
}
render() {
return (
<div>
<form className="form" id="addItemForm">
<input type="text" onChange={this.FirstName} placeholder="Enter First Name"/>
<input type="text" onChange={this.LastName} placeholder="Enter Last Name"/>
<input type="text" onChange={this.Email} placeholder="Enter Email"/>
<input type="password" onChange={this.Password} placeholder="Enter Password"/>
<button onClick={this.register} color="success" block>Create Account</button>
</form>
</div>
);
}
}
export default Reg;
This is what my Flask API has
@main.route('/createUser', methods=['POST', 'OPTIONS'])
def createUser():
conn = connection()
cur = conn.cursor()
req = request.get_json()
first = req.get('FirstName')
last = req.get('LastName')
email = req.get('Email')
pw = req.get('Password')
sql = "INSERT INTO User (first, last, emailAddress, password) VALUES (?, ?, ?, ?)"
data = (first, last, email, pw)
cur.execute(sql, data)
conn.commit()
cur.close()
return 'Done', 201
I've tried changing my JSON in case it was malformed, but it didn't change anything. I also tried posting from postman and it works fine from there so I'm thinking its the javascript.
console.logthem and post a snippet in here?