Node.js中使用Axios发送GraphQL请求遇JSON序列化解析错误
解决Axios发送Shopify GraphQL请求时的解析错误
问题根源
你的报错是因为GraphQL服务器无法解析请求中的body参数,核心原因有两个:
- 手动构造
body的转义JSON字符串,再配合外层的JSON.stringify,导致双重转义,服务器收到的body是一个被转义两次的字符串,而非可解析的JSON对象。 - Axios会自动将
data字段的对象序列化为JSON字符串,你提前调用JSON.stringify属于重复操作,加剧了格式混乱。
解决方法
方法1:用对象构造body,在GraphQL查询中直接序列化
先把body定义为普通JS对象,再通过JSON.stringify直接插入到GraphQL模板字符串中,同时直接给Axios传递对象而非预序列化的字符串:
var axios = require('axios'); // 定义body的原始对象,无需手动转义 const bodyData = { trigger_id: "28a17088-92d7-42e7-a1f2-3594fc4b8bf9", resources: [ { name: "AppName", url: "https://app.doman.com" } ], properties: { product_id: 3665695899753, Rating: 5, Author: "John Kendy", Email: "cauhaibg@gmail.com", "Country Code": "VN" } }; var config = { method: 'post', url: 'https://{shop_domain}/admin/api/2023-01/graphql.json', headers: { 'X-Shopify-Access-Token': 'xxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json' }, // 直接传对象,Axios会自动处理JSON序列化 data : { query: `mutation { flowTriggerReceive(body: ${JSON.stringify(bodyData)}) { userErrors { field, message } } }`, variables: {} } }; axios(config) .then(function (response) { console.log(JSON.stringify(response.data)); }) .catch(function (error) { console.log(error); });
方法2:使用GraphQL变量(推荐)
这是更规范的GraphQL用法,将body作为变量传递,避免在查询字符串中嵌套JSON:
var axios = require('axios'); const bodyData = { trigger_id: "28a17088-92d7-42e7-a1f2-3594fc4b8bf9", resources: [ { name: "AppName", url: "https://app.doman.com" } ], properties: { product_id: 3665695899753, Rating: 5, Author: "John Kendy", Email: "cauhaibg@gmail.com", "Country Code": "VN" } }; var config = { method: 'post', url: 'https://{shop_domain}/admin/api/2023-01/graphql.json', headers: { 'X-Shopify-Access-Token': 'xxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json' }, data : { // 定义带变量参数的mutation query: `mutation($body: JSON!) { flowTriggerReceive(body: $body) { userErrors { field, message } } }`, // 传递变量值 variables: { body: bodyData } } }; axios(config) .then(function (response) { console.log(JSON.stringify(response.data)); }) .catch(function (error) { console.log(error); });
关键注意点
- 永远不要手动构造带转义字符的JSON字符串,直接用JS对象配合
JSON.stringify或GraphQL变量处理。 - Axios的
data参数如果是对象,会自动序列化为JSON,无需提前调用JSON.stringify,否则会导致双重转义。
内容的提问来源于stack exchange,提问作者Be Duc Tai
相关产品推荐
相关产品推荐

