JSON:使用 Pexels API 键

JSON: Use Pexels API key

我开始学习 JSON,在我的整个旅程中,我在使用 API 时没有遇到过 API 键。我正在尝试处理像素 API,可在此处 https://www.pexels.com/api/documentation/?language=javascript 找到。我得到了一个 API 密钥,我如何在 JSON 中使用它。我知道这是一个荒谬的问题,但我一直无法找出答案。感谢您的帮助。

如果您阅读文档,他们会提供如何使用您的 API_KEY。

您可以查看文档 here

您必须在请求 header 中将 API_KEY 作为 Authorization 传递。

curl -H "Authorization: YOUR_API_KEY" \
  "https://api.pexels.com/v1/search?query=people"

JS

fetch("https://api.pexels.com/v1/search?query=people", {
  headers: {
    Authorization: 'YOUR_API_KEY'
  })
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(err => console.log(err))

首先,我建议您在项目的根目录中创建一个名为 .env.local

的 env 文件

然后将密钥添加到此 env 文件

YOUR_API_KEY = '1232123123123123123'  <== your key insted of these random numbers

然后您可以安全地使用您的密钥进行提取调用,然后像这样访问一些 pexels endopint

export const getDataFromApi = async () => {
  const res = await fetch(
  ENDPOINT_URL,
  {
    headers: {
      Authorization: API_KEY,
    },
  }
);
  const responseJson = await res.json();
  return responseJson.photos;
};