简体   繁体   中英

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.

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);
    });

Try also to do it like this without setting defaults:

axios.get('https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks', {
      headers: { "X-Mashape-Key": "MY_API_KEY" }
    })
      .then((resp) => {
        console.dir(resp);

      })
      .catch(err => {
        console.log(err);
      });
  }

It should work.

PS I also observed that you use different header keys in question(X-Mashape-Authorization) and answer(X-Mashape-Key). Maybe that is also somehow related to 404 error?

I got better way to solve this .

You just need add parameters format from axios like this below:

 axios({ method: <method>, url: <url>, data: <params>, headers: { common: <headers> }, }) .then(response => { if (!cb) return { error: 'No callback' }; return cb(response); }) .catch((err) => cb(err.response)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM