【发布时间】:2021-04-04 18:45:18
【问题描述】:
快速提问:我为我的 Strapi CMS 创建了一个 API 获取函数,但似乎无法获得正确的 JSON。 这导致我的 API 调用在 Strapi CMS (200 OK HTTP) 中添加了一个新项目。但没有提供的数据。我猜是 JSON 格式错误导致数据丢失。
什么有效:
- 授权有效
- API 请求有效 (200)
- Strapi CMS 中有一篇空文章
什么不起作用:
- CMS 中未设置数据。 代码:
// POST request using fetch with error handling
function setArticle() {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${state.jwt}`
},
body: JSON.stringify({
slug: "first-success",
name: "First successful API request"
})
};
fetch('http://localhost:1337/articles', requestOptions)
.then(async response => {
const data = await response.json();
console.log(requestOptions);
// check for error response
if (!response.ok) {
// get error message from body or default to response status
const error = (data && data.message) || response.status;
return Promise.reject(error);
}
this.setState({ postId: data.id })
})
.catch(error => {
console.error('There was an error!');
});
}
我尝试了什么,记录和阅读 Strapi 文档。
【问题讨论】:
标签: reactjs fetch gatsby strapi