node.js - Apollo 客户端 : Variable is not defined. 收到状态码 400

标签 node.js graphql apollo-client

我正在尝试使用 Apollo Client 在 GraphQL 查询中使用动态变量。我已按照文档进行操作,但 Apollo 一直给我错误,说我的变量未定义,并最终以状态码 400 响应。

这是 Apollo 的文档所说的:

mutate: (options?: MutationOptions) => Promise A function to trigger a mutation from your UI. You can optionally pass variables, optimisticResponse, refetchQueries, and update in as options, which will override any props passed to the Mutation component. The function returns a promise that fulfills with your mutation result.

这是我尝试编写的代码:

const fetch = require('node-fetch');
const ApolloClient = require('apollo-boost').default;
const gql = require('graphql-tag');

const client = new ApolloClient({
    uri: "http://api.domain.com/graphql",
    fetch
});

run();

async function run() {
    try {
        const resp = await client.mutate({
            mutation: gql`mutation {
                trackPr(id: $id, pr: $pr, title: $title, body: $body, state: $state, merged: $merged) {
                    id
                }
            }`,
            variables: {
                id: 1,
                pr: 1,
                title: "test title",
                body: "test body",
                state: "test state",
                merged: false
            },
        });


        console.log(resp.data);
    } catch(ex) {
        console.log(ex);
    }
}

然后我会收到每个变量的错误消息,说明它尚未定义:

[GraphQL error]: Message: Variable "$id" is not defined., Location: [object Object],[object Object], Path: undefined

在每条错误消息之后,我都会收到一条状态代码为 400 的最终消息:

[Network error]: ServerError: Response not successful: Received status code 400

突变本身在没有变量和直接在突变中设置所有值的情况下运行良好,但我不知道为什么它认为变量未定义。

最佳答案

操作中使用的任何变量都必须声明为操作定义的一部分,如下所示:

mutation SomeOptionalMutationName ($id: ID!) {
  trackPr(id: $id) {
    id
  }
}

这允许 GraphQL 根据提供的类型验证您的变量,并验证变量是否被用于代替正确的输入。

关于node.js - Apollo 客户端 : Variable is not defined. 收到状态码 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54329598/

相关文章:

node.js - Mongoose无法连接: Error: querySrv ENOTIMP mongodb. tcp.cluster1-owfxv.mongodb.net

node.js - Bot 框架中的上下文管理 - Node JS

typescript - 如何将自定义标量导入 NestJs 中的 .graphql 文件?

python - Graphql 不接受带引号的键

vue.js - 如何为 Vue Apollo 导入 Apollo Client 3?

ios - 设置默认缓存策略 apollo swift

vue.js - 为什么 Apollo/GraphQL 返回一个不可扩展的对象?

node.js - 强制网络服务器返回未压缩的数据(无 gzip)

java - 单向链表 - get 和 add 方法

elasticsearch - 使用 Elasticsearch 时查询响应大小是否有限制?