如何通过Axios在GraphQL查询中传递数组?
如何用Axios在GraphQL查询中发送数组
当然可以实现,先看看你现有代码里的几个问题:
reduce逻辑写错了:你用offer解构,但变量名是product,而且reduce会把数组转成单个对象,完全不是你要的数组格式。- 用
JSON.stringify生成的字符串带引号键,不符合GraphQL语法——GraphQL输入对象的字段名不需要加引号,只有字符串值需要。
下面给你两种不依赖额外包的解决方案:
方案一:使用GraphQL变量(推荐)
这是GraphQL的标准用法,把数组作为变量传入,不用手动拼接查询字符串,彻底避免语法问题:
const products = [{ id: 1, name: 'laptop', price: 500 }, { id: 2, name: 'book', price: 3 }]; // 定义带变量的GraphQL查询 const query = ` mutation SampleService($customerId: String!, $purchaseItems: [PurchaseItemInput!]!) { sampleService(customerId: $customerId, purchaseItems: $purchaseItems) { sessionId } } `; axios({ method: "POST", url: "https://sample.com/", timeout: 10000, headers: { 'Content-Type': 'application/json', 'Authorization': sample_token }, data: { query, variables: { customerId: customerId, // 传入你的customerId变量 purchaseItems: products } }, }) .then((response) => { return response.data; }) .catch((error) => { console.log('error', error) });
注意:PurchaseItemInput是你GraphQL服务定义的输入类型,要和后端保持一致,如果后端类型名不同,替换成对应名称即可。这种方式不需要手动处理数组格式,Axios会自动把变量序列化为正确的JSON,GraphQL服务能直接解析。
方案二:手动生成符合GraphQL语法的数组字符串
如果你一定要手动拼接查询字符串,可以写个简单函数把数组转成GraphQL格式:
const products = [{ id: 1, name: 'laptop', price: 500 }, { id: 2, name: 'book', price: 3 }]; // 把对象转成GraphQL输入格式的字符串 function objToGraphQLInput(obj) { return Object.entries(obj).map(([key, value]) => { // 字符串类型的值加引号,数字/布尔值直接输出 const formattedValue = typeof value === 'string' ? `"${value}"` : value; return `${key}: ${formattedValue}`; }).join(', '); } // 把数组转成GraphQL数组格式 const productsQuery = products.map(item => `{${objToGraphQLInput(item)}}`).join(', '); // 拼接查询字符串 const queryBody = `{sampleService(customerId: "${customerId}", purchaseItems: [${productsQuery}]) {sessionId}}`; axios({ method: "POST", url: "https://sample.com/", timeout: 10000, headers: { 'Content-Type': 'application/json', 'Authorization': sample_token }, data: { query: queryBody, }, }) .then((response) => { return response.data; }) .catch((error) => { console.log('error', error) });
这个函数会处理对象的每个字段:字符串值加引号,字段名不加引号,最后拼成符合GraphQL语法的数组字符串。
内容的提问来源于stack exchange,提问作者hi1989
相关产品推荐
相关产品推荐

