I'm trying to make a post request to an API that I created with mysql and node js using react and axios. But when I input in the data the response i get is 'undefined'. When I put the data with postman, it works. I tried to log the data that I sent with my browser and I saw them. So I think that maybe the structure
When i console.log the data in the browser, I can figure out those data
adapter: ƒ xhrAdapter(config)
data: "{"etudiants":{"name":"Fenohasina
Andrainiony","lastname":"fenohasina","birthdate":"12-12-12"}
So i think that maybe, the structure of the data I sent is different to the structure I can receive on my API because on my API: it is just
{"name":"Fenohasina
Andrainiony","lastname":"fenohasina","birthdate":"12-12-12"}
Is this the problem?
This is the api code:
app.post('/etudiants/add', (req, res)=>{
const {name,
lastname,
birthdate,
} = req.query;
const queryInsert =`insert into etudiants (name, lastname, birthdate) values('${name}', '${lastname}', '${birthdate}')`
connection.query(queryInsert, (err, rows, fields)=>{
if(err) {
throw err
}
res.json(rows);
res.end()
})
} }`
And the React Code:
export default class PersonList extends React.Component {
state = {
name:'',
lastname:'',
birthdate:'',
}
handleSubmit = event => {
event.preventDefault();
const etudiants = {
name: this.state.name,
lastname:this.state.lastname,
birthdate:this.state.birthdate,
};
axios.post('http://localhost:8080/etudiants/add', {etudiants})
.then(res=>{
console.log(res);
console.log(res.data)
})
}
handleName = event => {
this.setState({
name: event.target.value
})}
handleLastname = event => {
this.setState({
lastname: event.target.value,
})}
handleBirthdate = event => {
this.setState({
birthdate: event.target.value
})}
render() {
return (
<div className='App'>
<form onSubmit={this.handleSubmit}>
<label>
Person Name:
<input type="text" name="name" id='name'value={this.state.name} onChange={this.handleName} />
</label>
<label>
Person Lastname:
<input type="text" name="lastname" id='lastname'value={this.state.lastname} onChange={this.handleLastname} />
</label>
<label>
Person birthdate:
<input type="text" name="genre" id='birthdate'value={this.state.birthdate} onChange={this.handleBirthdate} />
</label>
<button type="submit">Add</button>
</form>
</div>
)
Thank you in advance!