[英]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 5tbuMbqNN0ychuxk973ZNA==='
},
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
或捕获异常中,所以它失败了,因为该插件无法获取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.