我正在尝试呼叫 Freesound API。 Fetch 抛出 Unauthorized 错误,而 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));
答案 0 :(得分:-1)
首先,您应该切勿在任何公共平台上发布 API 密钥,因为任何人都可以访问和利用您本应付费购买的 API。
您使用的端点似乎无效。此外,除非 opaque request 满足您的需要,否则不要使用 mode: 'no-cors'
。否则,您将无法访问响应对象中的任何属性。
401 错误的原因:使用 no-cors
会阻止在您的请求中添加 Authorization 标头。
克服 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));