无法从 Strapi API 获取数据到 next.js 前端 [英] Can't fetch data from Strapi API to next.js frontend
本文介绍了无法从 Strapi API 获取数据到 next.js 前端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试过使用 Strapi 和 next.js 来制作博客网站.这是前端代码的next.js
从next/head"导入头部从'../styles/Home.module.css' 导入样式导出默认函数首页({帖子}){返回 (<div>{帖子&&post.map((posts) => (<div key={post.id}><h2>{posts.title}</h2>
))}
);}导出异步函数 getstaticProps() {//从我们的API获取帖子const res = await fetch("http://localhost:1337/posts");const 帖子 = 等待 res.json();返回 {道具:{帖子},};}
这里是 Strapi API Json 数据
[{身份证":1,"title": "大家好","slug": "大家好","content": "大家好.",users_permissions_user":{身份证":4,"username": "tanha","email": "tanha@test.com","提供者": "本地",确认":真实,阻止":假,角色":1,"created_at": "2021-03-12T06:02:44.726Z","updated_at": "2021-03-12T06:03:54.507Z"},"published_at": "2021-03-11T19:37:02.117Z","created_at": "2021-03-11T19:36:46.663Z","updated_at": "2021-03-12T11:48:57.275Z"}]
这里有什么问题?我尝试过,但在这里没有发现任何错误.但是无法获取数据到前端显示.
解决方案
getstaticProps
应该在不同的情况下 ->getStaticProps
,除此之外你的代码看起来还不错.
I'm tried strapi and next.js to make a blog site. Here is next.js for frontend code
import Head from 'next/head'
import styles from '../styles/Home.module.css'
export default function Home({ posts }) {
return (
<div>
{posts &&
posts.map((posts) => (
<div key={post.id}>
<h2>{posts.title}</h2>
</div>
))}
</div>
);
}
export async function getstaticProps() {
//get post from our API
const res = await fetch("http://localhost:1337/posts");
const posts = await res.json();
return {
props: { posts },
};
}
and Here is Strapi API Json data
[
{
"id": 1,
"title": "Hello Everyone",
"slug": "hello-everyone",
"content": "Hello All.",
"users_permissions_user": {
"id": 4,
"username": "tanha",
"email": "tanha@test.com",
"provider": "local",
"confirmed": true,
"blocked": false,
"role": 1,
"created_at": "2021-03-12T06:02:44.726Z",
"updated_at": "2021-03-12T06:03:54.507Z"
},
"published_at": "2021-03-11T19:37:02.117Z",
"created_at": "2021-03-11T19:36:46.663Z",
"updated_at": "2021-03-12T11:48:57.275Z"
}
]
What is the problem in here? I was tried but found no errors in here. But can't fetch data into frontend to show.
解决方案
getstaticProps
should be in different case -> getStaticProps
, other than that your code looks fine.
这篇关于无法从 Strapi API 获取数据到 next.js 前端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文