Gatsby API 构建时间请求

Gatsby API Request on Build Time

我有一个 gatsby 项目,我需要在其中发出 API 请求以获取我将用于为每辆汽车动态创建页面的汽车列表。 API 响应数据是这样的:

{
  "Fleet_Data": [
      {
          "Make": "Honda",
          "Model": "Pilot"
      },
      {
          "Make": "Honda",
          "Model": "CRV"
      },
      {
          "Make": "Honda",
          "Model": "Accord"
      }
  ]
}

我正在使用 gatsby-source-custom-api 插件。这是我的 gatsby-config.js 文件:

{
  resolve: "gatsby-source-custom-api",
  options: {
    url: "https://api.fleetdata.com/",
    headers: {
      Authorization: 'Basic API_KEY'
    },
    rootKey: "Fleet_Data",
    schemas: {
      Fleet_Data: `
                    Make: String
                    Model: String
                `
    }
  }
}

除了调试之外,我的节点文件中没有任何内容,但这是我的 gatsby-node.js

const path = require("path");

exports.createPages = async ({ graphql }) => {
  console.log("IT WORKED")
};

但是当我 运行 gatsby build 我在控制台中收到以下错误:

"gatsby-source-custom-api" threw an error while running the sourceNodes lifecycle:

invalid json response body at https://api.fleetdata.com/ reason: Unexpected token : in JSON at position 4

  23 |
  24 |   const URL = getUrl(process.env.NODE_ENV, url)
> 25 |   const data = await fetch(URL).then(res => res.json())
     |                ^
  26 |
  27 |   const typeDefs = getTypeDefs(schemas, imageKeys)
  28 |   createTypes(typeDefs)

File: node_modules/gatsby-source-custom-api/gatsby-node.js:25:16



  FetchError: invalid json response body at https://api.fleetdata.com/ reason: Unexpected token : in JSON at position 4
  
  - index.js:272 
    [ProjectCars]/[node-fetch]/lib/index.js:272:32
  
  - task_queues.js:95 processTicksAndRejections
    internal/process/task_queues.js:95:5
  
  - gatsby-node.js:25 Object.exports.sourceNodes
    [ProjectCars]/[gatsby-source-custom-api]/gatsby-node.js:25:16
  
  - api-runner-node.js:429 runAPI
    [ProjectCars]/[gatsby]/src/utils/api-runner-node.js:429:16
  

not finished source and transform nodes - 3.913s

我做错了什么?

通常此问题是由 undefined API 响应引起的,通常是由服务器停机、错误配置等引起的。

在你的情况下,我已经使用 Postman 对其进行了测试,它抛出了一个错误:https://api.fleetdata.com/ 没有响应,所以因为你没有将它包装在 try/catch 中或捕获异常,它失败,因为插件无法获取数据。

或者,由于您将实施委托给第三方插件,我认为如果不进行 PR 或 tweaking/customizing 插件,没有办法解决此问题。您的实现非常“基本”或标准,因此要修复它,您可能需要打开作者存储库的线程。

您始终可以向 API 添加 fetch 请求并相应地自定义给定节点。

这已通过 gatsby-node.js 文件中的简单提取 api 调用解决,而不是使用插件。尽管有名称和文档,gatsby-source-custom-api 插件似乎并不打算用于这种特殊情况..