Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - How authorise a Fetch call with Authorisation Token?

I am trying to call a Freesound API. Fetch throws an Unauthorised error whereas Postman works.

Code

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)); 
question from:https://stackoverflow.com/questions/65643695/how-authorise-a-fetch-call-with-authorisation-token

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, you should never post API Key on any public platform as anyone can access and exploit the API that you would have paid for.

Solution

The endpoint you're using seems to be invalid. Also, don't use mode: 'no-cors' unless an opaque request serves your need. Else, you won't be able to access any property in the response object.

Reason of 401 error: Using no-cors prevents Authorization header to be added in your request.

Getting past CORS error: It usually happens in localhost during development. You can use an extension which would allow CORS.


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...