Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't do a request that needs to set a header with axios

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.

like image 235
Mehdi Brillaud Avatar asked Jun 30 '16 12:06

Mehdi Brillaud


People also ask

How do I set all HTTP headers in Axios?

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

How do I automatically set the Authorization header for all requests?

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.

How do I get data from a server using Axios?

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.

How do I send HTTP requests with Axios?

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.


Video Answer


1 Answers

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);
    });
like image 58
Mehdi Brillaud Avatar answered Oct 12 '22 13:10

Mehdi Brillaud