1

I'm trying to push to /home if status==200 ok but it's giving me an error.

 handleSubmit = (e) => {
   e.preventDefault();
   const form = this.props.form;
     const { password, username } = this.state;
   let data = new FormData(); // creates a new FormData object
   data.append('username', form.getFieldValue('username'));
   data.append('password', form.getFieldValue('password'));
   axios.post('http://127.0.0.1:8000/user/login/', data)
   .then(res=>console.log(res))
   .then(data => { if(data.status == 200){ history.push('/home');}})
   .catch(err=>console.log(err))

 };

It renders this:

{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}

TypeError: Cannot read property 'status' of undefined

Vencovsky
  • 28,550
  • 17
  • 109
  • 176
hpPh
  • 63
  • 1
  • 1
  • 11
  • Why do you use .then second time? axios.post('http://127.0.0.1:8000/user/login/', data) .then(data => { if(data.status == 200){ history.push('/home');}}) .catch(err=>console.log(err)). This should work. – Raja Sekar May 22 '19 at 11:42

3 Answers3

3

The reason why you cant read data.status is that data is undefined.

To get the data and the status, you need to return res so it's accesible in the next .then

Change this

.then(res=>console.log(res)) // data comes from the return of this function
.then(data => { if(data.status == 200){ history.push('/home');}})

To

.then(res => { 
    console.log(res)
    return res // data comes from the return of res
 }) 
.then(data => { if(data.status == 200){ history.push('/home');}})

If you aren't return something from .then, the next .then function parameter will be undefined.

Paraphrasing this answer

When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value.

In your case, you are returning console.log(res) wich don't have status property

Vencovsky
  • 28,550
  • 17
  • 109
  • 176
2

Replace

axios.post('http://127.0.0.1:8000/user/login/', data)
    .then(res=>console.log(res))
    .then(data => { if(data.status == 200){ history.push('/home');}})
    .catch(err=>console.log(err))

with

axios.post('http://127.0.0.1:8000/user/login/', data)
    .then(res => (res.status === 200) && history.push('/home'));
    .catch(err=>console.log(err))

I would suggest not to use data keyword here, this will create ambiguity as your API result has data keyword in it. Try always using triple equal to (===) in js comparisons.

Nayan shah
  • 543
  • 3
  • 8
0

Replace your url : 'http://127.0.0.1:8000/user/login/' to 'http://127.0.0.1:8000/user/login'

tell me if it works

Ucef Idel
  • 37
  • 4