Shopify前端调用GraphQL接口时遭遇CORS错误求助
解决Shopify前端调用GraphQL API的CORS错误
问题原因
你直接在前端调用的是Shopify Admin GraphQL API,这个API是给后端服务设计的——Shopify为了防止管理员令牌泄露,直接限制了前端浏览器的跨域请求,所以会触发CORS错误。而且把管理员令牌(X-Shopify-Access-Token)暴露在前端代码里,会直接导致店铺权限泄露,风险极高。
可行解决方案
方案1:改用Shopify Storefront API(推荐)
Storefront API是Shopify专门给前端应用准备的,支持跨域请求,不需要管理员令牌,只用Storefront API密钥即可,权限仅限只读商品数据,完全匹配前端获取产品信息的需求。
修改后的代码示例:
const response = await fetch(`https://test-store.myshopify.com/api/2023-04/graphql.json`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Storefront-Access-Token': "你的Storefront API密钥", }, body: JSON.stringify({ query: ` { product(id: "gid://shopify/Product/${productId}") { variants(first: 10) { edges { node { id inventoryItem { id } } } } } } `, }), });
注意事项:
- Storefront API的ID格式为
gid://shopify/Product/xxx,需要把原productId转换成这种格式 - 要在Shopify后台生成Storefront API密钥(路径:设置→应用和销售渠道→开发应用→创建应用→配置Storefront API权限)
方案2:搭建后端代理
如果必须使用Admin API(比如需要修改数据或访问Storefront API没有的字段),就得自己写一个后端接口:前端调用自己的后端服务,由后端去请求Shopify Admin API。这样管理员令牌存放在后端,不会泄露,同时避开了CORS限制。
简单的Node.js代理示例(基于Express):
const express = require('express'); const fetch = require('node-fetch'); const app = express(); const port = 3000; app.use(express.json()); app.post('/api/get-product', async (req, res) => { const { productId } = req.body; try { const response = await fetch(`https://test-store.myshopify.com/admin/api/2023-04/graphql.json`, { method: 'POST', headers: { 'Content-Type': 'application/graphql', 'X-Shopify-Access-Token': "你的管理员令牌", }, body: JSON.stringify({ query: ` { product(id: "${productId}") { variants(first: 10) { edges { node { id inventoryItem { id } } } } } } `, }), }); const data = await response.json(); res.json(data); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(port, () => { console.log(`代理服务运行在 http://localhost:${port}`); });
前端调用代理接口的代码:
const response = await fetch(`http://localhost:3000/api/get-product`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ productId: "你的产品ID" }), });
方案3:使用Shopify AJAX API(简单场景)
如果只是获取基础产品信息,也可以用Shopify的AJAX API,代码更简洁:
const response = await fetch(`https://test-store.myshopify.com/products/${productHandle}.js`); const productData = await response.json();
这个API支持跨域,返回JSON格式的产品数据,适合需求简单的场景。
内容的提问来源于stack exchange,提问作者The Rock
相关产品推荐
相关产品推荐

