I can't do a request that needs to set a heade

2019-06-21 20:54发布

问题:

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.

回答1:

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?



回答2:

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


回答3:

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