如何将Hygraph中的帖子数据展示到React应用中
解决React连接Hygraph获取帖子数据的问题
第一步:排查基础配置问题
- 确认API地址正确性:Hygraph的API端点格式为
https://api-us-west-2.hygraph.com/v2/{项目ID}/master,需替换为你项目的实际地址,可在Hygraph控制台「设置」→「API访问」中获取。 - 验证API令牌权限:若为公共读取接口,使用永久授权令牌(Public API Key),确保令牌勾选「查询(Query)」权限且无IP限制;私有内容需使用对应权限的令牌。
- 检查GraphQL查询语法:确保查询中的字段(如
komunikaty、date等)与Hygraph模型定义完全一致(大小写敏感),可先在Hygraph的API playground中测试查询是否返回有效数据。
第二步:修正Fetch请求代码
以下是修复后的Fetch示例,处理了常见格式与错误捕获问题:
import React, { useState, useEffect } from 'react'; const PostList = () => { const [posts, setPosts] = useState([]); // 替换为你的Hygraph API地址和令牌 const API_URL = 'https://api-us-west-2.hygraph.com/v2/your-project-id/master'; const API_TOKEN = 'your-public-api-key'; useEffect(() => { const fetchPosts = async () => { try { const response = await fetch(API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', // 公共接口也可使用 `Authorization: apikey ${API_TOKEN}` 格式 Authorization: `Bearer ${API_TOKEN}`, }, body: JSON.stringify({ query: ` query GetPosts { komunikaty { id title date publishedAt } } `, }), }); if (!response.ok) { throw new Error(`HTTP错误:${response.status}`); } const result = await response.json(); // 处理GraphQL层面的错误 if (result.errors) { throw new Error(`GraphQL错误:${result.errors.map(e => e.message).join(', ')}`); } setPosts(result.data.komunikaty); } catch (error) { console.error('获取数据失败:', error); } }; fetchPosts(); }, []); return ( <div> <h1>我的帖子</h1> {posts.length === 0 ? ( <p>加载中...</p> ) : ( <ul> {posts.map(post => ( <li key={post.id}> <strong>{post.title}</strong> <p>发布时间:{new Date(post.publishedAt).toLocaleString()}</p> <p>日期:{post.date}</p> </li> ))} </ul> )} </div> ); }; export default PostList;
第三步:Axios实现方案
先安装依赖(npm install axios),以下是正确实现:
import React, { useState, useEffect } from 'react'; import axios from 'axios'; const PostList = () => { const [posts, setPosts] = useState([]); const API_URL = 'https://api-us-west-2.hygraph.com/v2/your-project-id/master'; const API_TOKEN = 'your-public-api-key'; useEffect(() => { const fetchPosts = async () => { try { const response = await axios.post( API_URL, { query: ` query GetPosts { komunikaty { id title date publishedAt } } `, }, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${API_TOKEN}`, }, } ); if (response.data.errors) { throw new Error(`GraphQL错误:${response.data.errors.map(e => e.message).join(', ')}`); } setPosts(response.data.data.komunikaty); } catch (error) { console.error('获取数据失败:', error); } }; fetchPosts(); }, []); // 渲染部分与Fetch示例一致 return ( <div> <h1>我的帖子</h1> {posts.length === 0 ? ( <p>加载中...</p> ) : ( <ul> {posts.map(post => ( <li key={post.id}> <strong>{post.title}</strong> <p>发布时间:{new Date(post.publishedAt).toLocaleString()}</p> <p>日期:{post.date}</p> </li> ))} </ul> )} </div> ); }; export default PostList;
第四步:Apollo Client实现方案
先安装依赖(npm install @apollo/client graphql),分两步配置:
1. 全局配置Apollo Client(如App.js)
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client'; import PostList from './PostList'; const client = new ApolloClient({ uri: 'https://api-us-west-2.hygraph.com/v2/your-project-id/master', headers: { Authorization: `Bearer your-public-api-key`, }, cache: new InMemoryCache(), }); function App() { return ( <ApolloProvider client={client}> <PostList /> </ApolloProvider> ); } export default App;
2. 编写查询组件
import React from 'react'; import { useQuery, gql } from '@apollo/client'; const GET_POSTS = gql` query GetPosts { komunikaty { id title date publishedAt } } `; const PostList = () => { const { loading, error, data } = useQuery(GET_POSTS); if (loading) return <p>加载中...</p>; if (error) return <p>出错了:{error.message}</p>; return ( <div> <h1>我的帖子</h1> <ul> {data.komunikaty.map(post => ( <li key={post.id}> <strong>{post.title}</strong> <p>发布时间:{new Date(post.publishedAt).toLocaleString()}</p> <p>日期:{post.date}</p> </li> ))} </ul> </div> ); }; export default PostList;
额外排查点
- Hygraph内容状态:确保帖子已设置为「已发布(Published)」状态,草稿内容无法通过公共API获取。
- CORS设置:本地开发遇CORS错误时,在Hygraph控制台「设置」→「API访问」中添加本地地址(如
http://localhost:3000)到「允许的来源」列表。
内容的提问来源于stack exchange,提问作者NewToReact
相关产品推荐
相关产品推荐

