1

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!

2 Answers 2

1

Yes the problem is with the data you send

It should be

axios.post('http://localhost:8080/etudiants/add', {...etudiants})

(note the spread operator ... so that your etudiants constant is expanded in the object you send. Otherwise it just creates a property named etudiants which contains the contents of your constant)


Your code uses the short notation introduced in ES6

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions


additionally you could re-use a single method for your input handling since they all do the same thing. So handleName, handleLastname and handleBirthdate could be replaced by just

handleInput = event => {
  const {name, value} = event.target;
  this.setState({
    [name]: value
  });
}

finally i think

<input type="text" name="genre" id='birthdate'

should really be

<input type="text" name="birthdate" id='birthdate'
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you guys! That explain the issue i got in the first time: the birthdate was undefined. Your method made my code more sample.
1

I think the problem is how you are extracting the request data in the backend. In the react code, this is how you are making the request to the server:

axios.post('http://localhost:8080/etudiants/add', {etudiants})

The default behavior of Axios, when used like this, is to JSON serialize the request data(i.e {etudiants}) Refrence.
In order to receive and use this data in the backend, you need to parse the JSON request body, if you are using a body-parser middleware like this one, that should already be done for you. Then, you can extract the request body like this:

const { 
    name,
    lastname,
    birthdate,
   } = req.body.etudiants;

Note how I replaced req.query with req.body and the addition of etudiants.

1 Comment

Thank you OTZ for your help. We sloved it.

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.