【问题标题】:Error when trying to authorize Axios get request尝试授权 Axios 获取请求时出错
【发布时间】:2019-08-04 21:56:51
【问题描述】:

我正在尝试使用 Axios 访问 Uber API,但遇到了一些麻烦。我已将这些数据插入 Postman,我得到了 200 响应代码,没有任何问题。但是,当我尝试拨打 Axios 电话时,我收到未经授权的响应代码 401。我能否获得一些帮助来查看我的代码以找出为什么我的授权无法在 Axios 上正常工作?

这是我引用的 Uber API 文档的链接。 Uber API Reference

getRide_Uber = async (addressOrigin, addressDestination) => {
  let origin = await geocodeAddress(addressOrigin);
  let destination = await geocodeAddress(addressDestination);

  const url = "https://api.uber.com/v1.2/estimates/price";

  const params = {
    params: {
      start_latitude: origin.lat,
      start_longitude: origin.lon,
      end_latitude: destination.lat,
      end_longitude: destination.lon
    }
  };

  const headers = {
    headers: {
      Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
    }
  };

  const response = await axios
    .get(url, params, headers)
    .then(function(response) {
      data = response.data;
    })
    .catch(function(error) {
      console.log(error);
    });
  return data;
};

如果有任何需要澄清的地方,请告诉我。谢谢!

【问题讨论】:

    标签: rest http axios postman


    【解决方案1】:

    不确定您是如何从 env 获取令牌的,但似乎服务器令牌没有正确传递,从 env 读取时可能有几个额外的字符。尝试首先使用程序本身中的硬编码令牌运行程序,一旦确定它不是代码问题,您可以将其移动到 config/env 中,然后调试 env 读取问题。

    【讨论】:

    • 感谢您的关注!在发布之前,我确实对密钥进行了硬编码,这让我怀疑这是问题所在。据您所知,格式是否正确?
    【解决方案2】:

    试试下面的语法,

      const config = {
        headers: {
          Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
        } 
        params: {
          start_latitude: origin.lat,
          start_longitude: origin.lon,
          end_latitude: destination.lat,
          end_longitude: destination.lon
        }
      };
    
      const response = await axios
        .get(url, config)
        .then(function(response) {
          data = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
      return data;
    

    还有一个方面 axios,在 Internet Explorer 和旧浏览器中不支持 async/await。所以也请检查您的浏览器版本。

    【讨论】:

    • 这明白了!!!非常感谢@Mukund。我接受了这个作为答案。为什么将其包装在配置中可以解决我的问题?
    • axios 'get' 方法采用 url 和配置对象,配置对象同时包含标头和参数。所以我们需要将它们包装成单个。
    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 2022-08-20
    • 2022-01-05
    • 1970-01-01
    • 2021-06-02
    • 2020-04-27
    • 2011-10-25
    • 2023-01-25
    相关资源
    最近更新 更多