Reputation: 39
I'm trying to send a put request to an API. To make it work, i have to send an Authorization token in the headers.
Here's my code :
updatePlaylist(id, name) {
axios.put(`${config.baseUrl}/playlists/${id}`, { headers: auth.getAuthHeader(), data: { name } })
.then(() => {
})
.catch(() => {
console.error('unable to update tasks');
});
},
Here's the getAuthHeader function :
getAuthHeader() {
console.log(localStorage.getItem('token'));
return {
Authorization: localStorage.getItem('token')
};
}
The returned token by the getAuthHeader function is the good one.
Now the problem is i always get a 401 error, with no Authorization in the headers. Instead of that, i see this in the Request Payload section when checking with Google Chrome inspector :
{headers: {,…}, data: {name: "test"}}
data
:
{name: "test"}
headers
:
{,…}
For some reason, my headers are sent with the data.
Anyone knows how to fix it ?
Thanks a lot
Upvotes: 0
Views: 671
Reputation: 545
The way you are invoking the axios.put
is incorrect. You are passing the headers in the data
of the put method, you need to send it as a config
argument.
axios.put(`${config.baseUrl}/playlists/${id}`, {
name
}, {
headers: {...getAuthHeader() //, {...otherHeaders} Incase you have to add other headers as well
}
})
When using the alias methods(post, put, get) the url, method, and data properties don't need to be specified in config. But information regarding
headers
will still go to the config argument.
Upvotes: 1