我正在尝试使用 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/