Home > Mobile >  401 authorization error when trying to fetch API key
401 authorization error when trying to fetch API key

Time:06-22

I am getting the following error when trying to fetch an API key from Spoonacular: code: 401 message: "You are not authorized. Please read As you see here just provide your api-key

Anyway maybe because you have to replace the single quotation with ` :

const api = await fetch(
  `https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&NUMBER=9`
);

CodePudding user response:

You should always call the API in Try catch, so that you can log the error and check if there is an error. 401 Status Unauthorized you must pass a Authorization token in the API 'Headers'.

const getPopular = async () => {
    const api = await fetch(
      `https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&NUMBER=9`, {
  headers: {
    'Authorization': // pass your token here
    }
     }
    );
    try {
      const data = await api.json();                 
      console.log(data);
    } catch (error) {
       console.log(error.response) 
    }
  };

CodePudding user response:

enter image description here

As you see bro , i checked that with the api-key you sent, it works like charm!

CodePudding user response:

This code on sandbox is working as expected :

import { useEffect, useCallback } from "react";

const apiKEY = "71e9601785ed4c919af2fa6f4e0bfe96";

function Popular() {
  const getPopular = useCallback(async () => {
    const api = await fetch(
      `https://api.spoonacular.com/recipes/random?apiKey=${apiKEY}&NUMBER=9`
    );
    const data = await api.json();
    console.log(">>>>>>>>>>>>", data);
  }, []);

  useEffect(() => {
    getPopular();
  }, [getPopular]);

  return <div>Popular</div>;
}

export default Popular;
Maybe you aren't storing the api-key properly in the .env file , just log process.env.REACT_APP_API_KEY to the console and see

  • Related