【问题标题】:How authorise a Fetch call with Authorisation Token?如何使用授权令牌授权 Fetch 调用?
【发布时间】:2021-04-15 00:40:52
【问题描述】:

我正在尝试拨打Freesound API。 Fetch 抛出未经授权的错误,而 Postman 有效。

代码

const BASE_URL = "https://freesound.org/apiv2/sounds/";
const rain = "58835";
const APIKEY = "foo";

const headers = {
   method: "GET",
    headers: {
      'Authorization': `Token ${APIKEY}`,
    },
   mode: "no-cors",
};

fetch(BASE_URL + rain, headers)
    .then((response) => response.json()) 
    .then((json) => console.log(json)) 
    .catch((err) => console.log(err)); 

【问题讨论】:

  • 您发布了您的 API 密钥。你现在需要买一个新的。不要这样做!
  • 在 Postman 上,您是否在响应中获得了 CORS 标头。具体来说,Access-Control-Allow-Origin?如果是这样,您可以将模式设置为cors,它应该可以工作。
  • 我在阅读了这些问题后写了an article about no-cors。希望对您有所帮助!

标签: javascript fetch-api


【解决方案1】:

首先,您应该永远不要在任何公共平台上发布 API 密钥,因为任何人都可以访问和利用您支付费用的 API。

解决方案

您使用的端点似乎无效。此外,除非opaque request 满足您的需要,否则不要使用mode: 'no-cors'。否则,您将无法访问响应对象中的任何属性。

401 错误的原因:使用no-cors 会阻止在您的请求中添加授权标头。

克服 CORS 错误: 它通常在开发过程中发生在 localhost 中。您可以使用允许 CORS 的 extension


const QUERY = 'piano';
const API_KEY = 'foo';
const BASE_URL = `https://freesound.org/apiv2/search/text/?query=${QUERY}`

const headers = {
  method: 'GET',
  headers: {
    Authorization: `Token ${API_KEY}`,
  }
};

fetch(BASE_URL, headers)
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((err) => console.log(err));

【讨论】:

  • no-cors 也会阻止设置授权标头
  • 感谢分享缺失的信息!
  • 感谢您的回答,但我得到了(“跨域请求被阻止:同源策略不允许读取freesound.org/apiv2/sounds/58835 的远程资源。(原因:CORS 请求未成功)。” ) 没有“no-cors”的错误。
猜你喜欢
  • 1970-01-01
  • 2021-02-20
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多