0
votes

I'm posting to an API using axios, and using the data from the response I want to make another API request but I'm running into issues saying that axios is not defined.

The calls, that are in inside my Vue login component, are the following:

this.axios({
  method: 'post',
  url: '/my_api/test',
  data: "testdata=test123",
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

.then(function (response) {
  this.axios({
    method: 'get',
    url: '/my_api/test2',
    data: "testdata2=" + response.data.id
  })
})

and as I mentioned earlier, the error in my console is the following: TypeError: Cannot read property 'axios' of undefined.

I´ve tried writing the second request without this. but I'm having the same issues. Where am I going wrong?

1

1 Answers

1
votes

You have to use an arrow function here.

Regular functions have their own this value.

this.axios({
  method: 'post',
  url: '/my_api/test',
  data: "testdata=test123",
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

.then(response => {
  this.axios({
    method: 'get',
    url: '/my_api/test2',
    data: "testdata2=" + response.data.id
  })
})

Or if you prefer old-fashioned way you can save this reference to some variable to have access to it in the callback:

const self = this

this.axios({
  method: 'post',
  url: '/my_api/test',
  data: "testdata=test123",
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

.then(function (response) {
  self.axios({
    method: 'get',
    url: '/my_api/test2',
    data: "testdata2=" + response.data.id
  })
})