How do I pass an ApiKey to my header using axios in a react js App

124 Views Asked by At

I was given an Apikey to pass alongside an endpoint as a get Request. I went to Postman and added the endpoint, then in the authorization section I selected Api Key, it showed me the key and values, in the key I placed ApiKey, and in the value, the actual value. When I sent it, it responded well with a status code 200. But in my React App, it returns 401 unauthorized. I suspect I am passing it wrongly or what am I doing wrong? This is my code below

Please I would appreciate any prompt feedback, thanks a lot

I tried to use this, but it showed unauthorized

  useState(() => {
        const getAcc = async () => {
            try {
                const res = await axios.get(url, {
                    headers: {
                        "Authorization":{
                            "API Key": `${api_key}`
                        }
                    }
                });
                console.log("resPonseAdd", res)
            } catch (error) {
                console.log("myError",error)
            }
        }

        getAcc()
    }, [])
2

There are 2 best solutions below

6
BetterReact Developer On

there is not much context given on the question but I can try to answer with an issue I am seeing in your code.

The Authorization header does not accept any random value, it needs some specific format, you can refer to this.

All the formats that a value can be passed to Authorization header. Generally most common is Basic {credentials in base 64} and Bearer {token} I am guessing in postman it was set to Basic, but you can refer to the actual API documentation where you recieved this API Key. Hope this solves your problem.

1
TARA CHAND KUMAWAT On
  try {
    const response = await axios.get(url, {
      headers: {
        'Authorization': `Bearer ${apiKey}`,
      },
    });

    console.log('Response:', response.data);
  } catch (error) {
    console.error('Error:', error);
  }
};

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