Shopify Admin API创建客户返回异常Gunzip响应求助
问题排查与修复方案
1. GraphQL请求语法错误(核心问题)
你的请求存在多处语法错误,这是导致异常的主要原因:
- 创建客户必须用mutation而非query,query仅用于读取数据,mutation才负责创建/修改数据
- 字符串类型参数(姓名、邮箱、密码等)需要用双引号包裹
- 字段赋值使用冒号
:而非等号=,字段间用逗号分隔,不能用分号结尾 - 正确调用Shopify的
createCustomer接口来创建客户
修正后的GraphQL请求(直接拼接值版本):
const shopifyUserMutation = ` mutation { createCustomer(input: { firstName: "${values.firstName}", lastName: "${values.lastName}", email: "${values.email}", verifiedEmail: true, password: "${values.password}", passwordConfirmation: "${values.password}", sendEmailWelcome: false }) { customer { id email } } } `;
如果参数包含特殊字符(如双引号),建议用GraphQL变量传递,避免语法错误和注入风险:
const shopifyUserMutation = ` mutation CreateCustomer($input: CustomerInput!) { createCustomer(input: $input) { customer { id email } } } `;
2. 响应Gunzip对象处理问题
你看到的Gunzip对象是因为Shopify默认返回gzip压缩的响应,Node.js环境下fetch不会自动解压,有两种处理方案:
- 方案一:禁用压缩
在请求头中添加Accept-Encoding: identity,告知Shopify不要压缩响应:headers: { 'X-Shopify-Access-Token': shopifyAdminAccessToken, 'Content-Type': 'application/json', 'Accept-Encoding': 'identity' } - 方案二:手动解压
使用Node.js的zlib模块处理压缩内容:const zlib = require('zlib'); const { promisify } = require('util'); const gunzip = promisify(zlib.gunzip); // 请求后处理响应 const responseBuffer = await shopifyUser.buffer(); const decompressedBuffer = await gunzip(responseBuffer); const responseData = JSON.parse(decompressedBuffer.toString()); console.log(responseData);
3. 完整请求示例(结合变量+禁用压缩)
const shopifyUserMutation = ` mutation CreateCustomer($input: CustomerInput!) { createCustomer(input: $input) { customer { id email } } } `; try { const shopifyUser = await fetch(process.env.SHOPIFY_ADMIN_API_URL, { body: JSON.stringify({ query: shopifyUserMutation, variables: { input: { firstName: values.firstName, lastName: values.lastName, email: values.email, verifiedEmail: true, password: values.password, passwordConfirmation: values.password, sendEmailWelcome: false } } }), method: 'post', headers: { 'X-Shopify-Access-Token': shopifyAdminAccessToken, 'Content-Type': 'application/json', 'Accept-Encoding': 'identity' }, }); if (!shopifyUser.ok) { const errorData = await shopifyUser.json(); console.error('请求错误:', errorData); return; } const data = await shopifyUser.json(); console.log('创建成功:', data); } catch (err) { console.error('网络/解析错误:', err); }
内容的提问来源于stack exchange,提问作者gregwhitworth
相关产品推荐
相关产品推荐

