Shopify应用开发:React传动态值至Express实现GraphQL Mutation
解决方案
核心思路
把硬编码的GraphQL mutation改成带变量的形式,同时调整Express路由为POST(更符合写操作的规范),在React端通过请求体传递动态值,这样就能实现动态参数的传递,同时复用GraphQL的逻辑。
步骤1:修改Express后端代码
- 将原GET路由改为POST,接收请求体中的动态参数
- 使用GraphQL变量替代硬编码值,避免字符串拼接的安全问题
修改后的Express代码:
// 确保先配置JSON解析中间件 app.use(express.json()); app.post("/api/collection", async (req, res) => { try { const session = res.locals.shopify.session; const client = new shopify.api.clients.Graphql({ session }); // 从请求体获取动态传入的集合ID和标题 const { collectionId, newTitle } = req.body; const response = await client.query({ // 定义带变量的mutation data: `mutation updateCollectionHandle($id: ID!, $title: String!) { collectionUpdate(input: {id: $id, title: $title}) { collection { title } userErrors { field message } } }`, // 传入变量值 variables: { id: collectionId, title: newTitle }, }); res.status(200).send(response); } catch (err) { res.status(500).send(err); } });
步骤2:修改React前端代码
在useAppQuery中指定POST方法,并将动态参数放在请求体中发送:
// 假设你有动态的集合ID和新标题(比如从组件状态或props获取) const [collectionId, setCollectionId] = useState("gid://shopify/Collection/123"); const [newTitle, setNewTitle] = useState("NEW NAME"); const { data } = useAppQuery({ url: "/api/collection", method: "POST", // 指定POST方法 body: JSON.stringify({ collectionId, newTitle }), // 传递动态参数 reactQueryOptions: { onSuccess: () => { setIsLoading(false); }, }, });
备选方案:如果useAppQuery不支持POST请求
如果useAppQuery仅支持GET请求,可以将动态参数放在URL的查询字符串中:
- React端:
const { data } = useAppQuery({ url: `/api/collection?collectionId=${collectionId}&newTitle=${encodeURIComponent(newTitle)}`, reactQueryOptions: { onSuccess: () => { setIsLoading(false); }, }, });
- Express端(保持GET路由):
app.get("/api/collection", async (req, res) => { try { const session = res.locals.shopify.session; const client = new shopify.api.clients.Graphql({ session }); // 从查询字符串获取参数 const { collectionId, newTitle } = req.query; const response = await client.query({ data: `mutation updateCollectionHandle($id: ID!, $title: String!) { collectionUpdate(input: {id: $id, title: $title}) { collection { title } userErrors { field message } } }`, variables: { id: collectionId, title: newTitle }, }); res.status(200).send(response); } catch (err) { res.status(500).send(err); } });
注意:GET方式传递敏感或特殊字符时需要编码,且不适合大数据量,优先推荐POST方案。
内容的提问来源于stack exchange,提问作者Smlok
相关产品推荐
相关产品推荐

