0

I have this block of code, and the post works perfectly fine if i comment out the .then part, but if i leave it in, the post will not go through. How might I go about fixing this?

      axios.post('http://localhost:5000/exercises/add', exercise)
                .then(res => console.log(res.data))
                .then(window.location.href = '/')
                .catch(err => console.log(err))

chow1340
  • 13
  • 4
  • 4
    Because you have a statement there.. It will get executed beforehand.. Wrap it in a function like `then(function(){window.location.href='/';})` – xxMrPHDxx Dec 09 '19 at 15:36

2 Answers2

4

window.location.href = '/' isn't a function

It gets evaluated immediately and the result is passed to then() (since the result isn't a function, this is useless).

Do what you did on the previous line:

  axios.post('http://localhost:5000/exercises/add', exercise)
        .then(res => console.log(res.data))
        .then(log_result => (window.location.href = '/'))
        .catch(err => console.log(err))

Better yet, since you aren't getting a promise back from console.log, just have the one then():

  axios.post('http://localhost:5000/exercises/add', exercise)
        .then(res => {
            console.log(res.data);
            window.location.href = '/';
        })
        .catch(err => console.log(err))
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You have 2 then for some reason which is not needed. Try combining the two together

axios.post('http://localhost:5000/exercises/add', exercise)
  .then(res => {
    console.log(res.data)
    window.location.href = '/'
  })
  .catch(err => console.log(err))
Radu
  • 540
  • 1
  • 7
  • 23