【问题标题】:How to provide values for graphlql query variables in vanilla javascript如何在 vanilla javascript 中为 graphql 查询变量提供值
【发布时间】:2021-05-26 00:07:31
【问题描述】:

我正在尝试为 graphql 查询中的变量提供值,但它不起作用。

const queryInfo = {
query: `query($username: String!){
        user(login: $username){
        name
        bio
        avatarUrl
        repositories(first: 20){
        nodes{
        name
        url
        forkCount
        stargazerCount
        updatedAt
        languages(first: 20) {
          nodes{
            name
          }
        }
        }
        }
        }
        }
        `,
        {username: "japhmayor"}


};
  const url = "https://api.github.com/graphql";
  const token = "my token is here";
  const options = {
  method: "POST",
  headers: {
  "Content-Type": "application/json",
  Authorization: "bearer " + token,
  },
  body: JSON.stringify(queryInfo),
  };

如果我对用户名进行硬编码,则查询效果很好。如何提供用户名变量的值?

【问题讨论】:

  • 原样的代码会发生什么?你有错误吗?
  • 是的。提取没有通过,因为用户名未定义。
  • 变量需要变量对象 - 使用 Playground 测试突变,探索请求详情
  • 我的查询在 github api explorer 中运行良好,但不知道如何在我的代码编辑器中提供变量值
  • 只要找出两个请求之间的区别

标签: javascript graphql


【解决方案1】:

您的queryInfo 还需要一个variables 对象,您可以在其中定义查询的变量。它看起来像这样:

const queryInfo = {
    query: `query($username: String!) {
                ..
           }`,
    variables: {
        username: 'japhmayor'
    }
}

查看the docs中的最后一个示例

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2019-02-15
    • 2022-01-24
    • 2019-04-11
    • 2018-02-05
    • 1970-01-01
    • 2021-05-22
    • 2019-05-17
    • 2023-03-12
    相关资源
    最近更新 更多