我在获取单个产品页面的数据时收到
POST 403 (forbidden)
错误消息,但是对于我的产品列表页面,获取功能工作得很好。请有人告诉我发生了什么事。
shopifyApi.jsx(导入到Products.jsx):
export const fetchProducts = async () => {
const response = await fetch(`https://<MyShopifyStore/>.myshopify.com/api/2024-10/graphql.json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': ''
},
body: JSON.stringify({
query: `
{
products(first: 5) {
edges {
node {
id
title
descriptionHtml
images(first: 1) {
edges {
node {
src
}
}
}
variants(first: 1) {
edges {
node {
priceV2 {
amount
}
}
}
}
}
}
}
}
`,
}),
});
const { data } = await response.json();
return data.products.edges;
};
Products.jsx(获取和显示工作正常):
import { fetchProducts } from '../../../api/shopifyApi.js'
const Products = () => {
const [productsList, setProductsList] = useState([]);
useEffect(() => {
const getProducts = async () => {
const productData = await fetchProducts();
setProductsList(productData)
};
getProducts();
}, []);
return (
<div className="product-container">
<div className='product-grid'>
{
productsList.map(({ node }) => (
<div
className='product-card'
key={node.id}
>
<Link
to={`/product/${node.productId}`}
reloadDocument
>
{node.images.edges.length > 0 && (
<img
src={node.images.edges[0].node.src}
alt={node.title}
width={300}
/>
)}
{/* <div dangerouslySetInnerHTML={{ __html: node.descriptionHtml }} /> */}
<h2>{node.title}</h2>
</Link>
<p>£{node.variants.edges[0].node.priceV2.amount}</p>
<button type='button'>ADD TO CART</button>
</div>
))
}
</div>
</div>
)
}
export default Products
ProductPage.jsx(由于某种原因,不起作用并得到
POST 403 (forbidden)
:
const ProductPage = () => {
const { productId } = useParams();
const [product, setProduct] = useState(null);
useEffect(() => {
const fetchProduct = async () => {
const response = await fetch(`https://<MyShopifyStore/>.myshopify.com/api/2024-10/graphql.json`, {
method: 'POST',
header: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': ''
},
body: JSON.stringify({
query: `
query {
product(id: "gid//shopify/Product/${productId}") {
edges {
node {
id
title
descriptionHtml
images(first: 1) {
edges {
node {
src
}
}
}
}
}
}
}
`
})
})
const { data } = await response.json();
setProduct(data?.product?.edges)
};
fetchProduct();
}, [productId])
if (!product) return <div>Loading...</div>
return (
<div className='product-page-container'>
<h1>{product.title}</h1>
{product.images.edges.length > 0 && (
<img src={product.images.edges[0].node.src} alt={product.title} />
)}
<div dangerouslySetInnerHTML={{ __html: product.descriptionHtml }}/>
</div>
)
}
export default ProductPage;
Products.jsx
页面显示产品,但ProductPage.jsx
页面出现错误。我做错了什么?请有人帮忙。谢谢。
有点晚了,但如果还没有找到解决方案......
您在单个产品查询中使用“edges”字段。这个查询是扁平的,比如:
query {
product(id: "gid//shopify/Product/${productId}") {
id
title
descriptionHtml
images(first: 1) {
edges {
node {
src
}
}
}
}
}
并且,作为提示,在 StorefrontAPI 上,更喜欢使用“handle”字段来查询产品而不是其 id。