I'm trying to get some datas from an external API (from Mashape) that requires a specific header to set the API key.
Everything is ok using jQuery :
$.ajax({
url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks',
type: 'GET',
data: {},
dataType: 'json',
success: function(data) { console.dir((data.source)); },
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "MY_API_KEY");
}
});
However, when I'm trying to do the same request with axios for a react application, I have a 404 error:
axios.get({
url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks',
headers: {
"X-Mashape-Authorization": "MY_API_KEY"
}
})
Is there something I'm missing ? Thanks.
Set Global Default Headers If you want to set common headers to all HTTP requests, then you use Axios config defaults to set headers axios.defaults.headers.common["Authorization"] = `Bearer $ {token}` Or you can set common headers to all POST requests as
We can use Axios interceptors to automatically set the Authorization header for all requests: In this example, we use the axios.interceptors.request.use method to update each request header and set the access token in the Authorization HTTP header.
Axios can make a GET request to “get” data from a server. The axios.get () method is used to make an HTTP get request. There are two parameters that must be passed to the get () method.
Sending HTTP requests with Axios is as simple as giving an object to the axios () function that contains all of the configuration options and data. Let's look at the configuration options in more detail: data: The data specified with this option is sent in the body of the HTTP request in POST, PUT, and PATCH requests.
I finally understood.
We need to set the header BEFORE the request using axios.defaults.headers.common['header_name'] = "API_KEY";
:
axios.defaults.baseURL = 'https://omgvamp-hearthstone-v1.p.mashape.com';
axios.defaults.headers.common['X-Mashape-Key'] = "API_KEY";
axios.get('/cardbacks')
.then((resp) => {
console.dir(resp);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With