我不能做一个需要用axios设置标头的请求

Meh*_*aud 5 javascript api http-headers axios

我正在尝试从外部API(来自Mashape)获取一些数据,这些数据需要特定的标头来设置API密钥.

使用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");
    }
});
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用axios为反应应用程序执行相同的请求时,我遇到404错误:

axios.get({
  url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks',
  headers: {
      "X-Mashape-Authorization": "MY_API_KEY"
   }
 })
Run Code Online (Sandbox Code Playgroud)

有什么我想念的吗?谢谢.

Meh*_*aud 14

我终于明白了.

我们需要在请求之前使用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);
    });
Run Code Online (Sandbox Code Playgroud)


Ale*_*eev 11

尝试这样做而不设置默认值:

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);
      });
  }
Run Code Online (Sandbox Code Playgroud)

它应该工作.

PS我还观察到您使用了不同的标题键(X-Mashape-Authorization)和答案(X-Mashape-Key).也许这也与404错误有某种关系?