如何使用身份验证令牌授权 Fetch 调用?

How authorise a Fetch call with Authorisation Token?

我正在尝试调用 Freesound API. Fetch throws an Unauthorised error whereas 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)); 

首先,你应该 永远不要 post API Key 在任何 public 平台上,因为任何人都可以访问和利用 API 你会付钱的。

解决方案

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

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

通过 CORS 错误: 它通常发生在开发过程中的本地主机中。您可以使用允许 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));