首页 > 解决方案 > GraphQL 查询 - 在 JSON 响应中看不到嵌套元素

问题描述

如果有人可以冒险猜测或在哪里看,将不胜感激。当我使用 graphgl API 运行时,我可以获得嵌套数据,但是,从我的节点程序中它只显示顶级项目 - 不显示客户和 lineitem 对象的嵌套元素。我正在使用 Koa 中间的地方,承诺响应:

router.get('/orders/', async (ctx) => {
const auth = prepareAuth(ctx);
await getOrders(auth).then(response => ctx.body = response.data.data.orders);

console.log(ctx.body.edges)

但是从控制台它有(客户空和'对象':

[
  {
    node: {
      createdAt: '2020-02-24T12:53:20Z',
      customer: null,
      name: '#1001',
      lineItems: [Object]
    }
  },
  {
    node: {
      createdAt: '2020-02-24T12:53:50Z',
      customer: null,
      name: '#1002',
      lineItems: [Object]
    }
  },
  {
    node: {
      createdAt: '2020-03-10T21:11:04Z',
      customer: null,
      name: '#1003',
      lineItems: [Object]
    }
  }
]

当我直接使用 GraphQL API 时,查询工作正常,我得到了完整的响应:

{
  "data": {
    "orders": {
      "edges": [
        {
          "node": {
            "createdAt": "2020-02-24T12:53:20Z",
            "customer": {
              "displayName": "franko girl"
            },
            "name": "#1001",
            "lineItems": {
              "edges": [
                {
                  "node": {
                    "name": "dance mat red",
                    "quantity": 4
                  }
                }
              ]
            }
          }
        },
        {
          "node": {
            "createdAt": "2020-02-24T12:53:50Z",
            "customer": {
              "displayName": "franko man"
            },
            "name": "#1002",
            "lineItems": {
              "edges": [
                {
                  "node": {
                    "name": "dance mat black",
                    "quantity": 2
                  }
                }
              ]
            }
          }
        },
        {
          "node": {
            "createdAt": "2020-03-10T21:11:04Z",
            "customer": {
              "displayName": "franko man"
            },
            "name": "#1003",
            "lineItems": {
              "edges": [
                {
                  "node": {
                    "name": "dance mat black",
                    "quantity": 1
                  }
                },
                {
                  "node": {
                    "name": "dance mat red",
                    "quantity": 1
                  }
                }
              ]
            }
          }
        }
      ]
    }
  },

标签: node.jsgraphql

解决方案


好的,所以终于想通了,对于遇到此问题的其他任何人,您需要使用内置的 javascript 函数将 json 对象转换为字符串:JSON.stringify()

来自 W3schools.com

var obj = { 姓名:“约翰”,年龄:30,城市:“纽约”};

var myJSON = JSON.stringify(obj);


推荐阅读