如何在 React js 应用程序中使用 axios 将 ApiKey 传递到我的标头

问题描述 投票:0回答:2

我获得了一个 APIkey,可以作为 get 请求与端点一起传递。我转到 Postman 并添加了端点,然后在授权部分中我选择了 Api Key,它向我显示了键和值,在键中我放置了 ApiKey,在值中放置了实际值。当我发送它时,它响应良好,状态代码为 200。但在我的 React 应用程序中,它返回 401 未经授权。我怀疑我传递错了或者我做错了什么?这是我的代码如下

请及时提供反馈,非常感谢

我尝试使用这个,但它显示未经授权

  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()
    }, [])
reactjs axios api-key request-headers
2个回答
0
投票

该问题没有给出太多上下文,但我可以尝试回答我在您的代码中看到的问题。

Authorization
标头不接受任何随机值,它需要一些特定的格式,您可以参考this

值可以传递到

Authorization
标头的所有格式。 一般来说,最常见的是
Basic {credentials in base 64}
Bearer {token}
我猜测在 postman 中它被设置为 Basic,但您可以参考收到此 API 密钥的实际 API 文档。 希望这能解决您的问题。


0
投票
  try {
    const response = await axios.get(url, {
      headers: {
        'Authorization': `Bearer ${apiKey}`,
      },
    });

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

useEffect(()=>{
   getAcc();
},[])
© www.soinside.com 2019 - 2024. All rights reserved.