我无法执行需要使用 axios 设置标头的请求 [英] I can't do a request that needs to set a header with axios

查看:34
本文介绍了我无法执行需要使用 axios 设置标头的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get some datas from an external API (from Mashape) that requires a specific header to set the API key.

使用 jQuery 一切正常:

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

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

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.

推荐答案

尝试在不设置默认值的情况下也这样做:

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

它应该可以工作.

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

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?

这篇关于我无法执行需要使用 axios 设置标头的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆