Alvin Mathis
Alvin Mathis

Reputation: 110

React Axios how to correctly pass in config as parameter?

Does anyone know how to pass in config in Axios? It works when the option that is passed in is "method:'GET'", but it won't work when options are "method:'POST,data:jsondata". it returns error 500 with 'GET' method. Why is it still a 'GET' method, is there a workaround or I'm doing it wrong? I want to call only this function when using Axios.

 fetchWithToken(url, options) {          
        const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' }
        if (this.loggedIn) {
            headers['Authorization'] = 'Bearer ' + this.getToken()
            return axios(url, { headers, options })
                .then(response => { return response })
        }
}

enter image description here

Upvotes: 2

Views: 4158

Answers (2)

Sirghi Mihail
Sirghi Mihail

Reputation: 125

There is a syntax problem with your method. You are passing the object which has another object, which you should use as parameter in your axios request.

I would do it like this:

 fetchWithToken = (url, options)=>{          
  const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' }
  if (this.loggedIn) {
      headers['Authorization'] = 'Bearer ' + this.getToken()
      return axios({url: url, headers: headers, data: options.data, method: options.method})
          .then(response => { return response })
   }
}

const obj = {method:'POST', data:""};
fetchWithToken(url, obj);

So you now can call fetchWithToken(url,{method:'POST',data:jsondata})

Upvotes: 1

Fatema Tuz Zuhora
Fatema Tuz Zuhora

Reputation: 3746

let postData = {
    // DATA FOR POST METHOD
}

axios({
    method: 'POST',
    url: `YOUR_API_ENDPOINT`,
    headers: {
        Authorization: `YOUR_AUTH_TOKEN`,
        "Content-Type": "application/json"
    },
    data: {
        ...postData
    }
})
.then((res) => {
    // YOUR CODE HERE
})
.catch((err) => {
    console.log(err);
});

Upvotes: 0

Related Questions