Apollo/GraphQL 突变在 GraphIQL 中有效,但在客户端代码中无效?
Posted
技术标签:
【中文标题】Apollo/GraphQL 突变在 GraphIQL 中有效,但在客户端代码中无效?【英文标题】:Apollo/GraphQL Mutation Works in GraphIQL, but Not in Client Code? 【发布时间】:2017-01-21 16:38:42 【问题描述】:我在 http://localhost:8080/graphiql 的 GraphIQL 中让这个突变正常工作:
查询
mutation($fromID: String!, $toID: String!, $msgText: String!)
createIM(fromID: $fromID, toID: $toID, msgText: $msgText)
fromID
toID
msgText
...和查询变量
"fromID": "1",
"toID": "2",
"msgText": "Test from GraphIQL #3. It's working!!!"
现在我需要在代码中实现它。
客户代码
sendInstantMsg()
const textToSend = this.refs;
const toID = this.props;
const fromID = Meteor.userId();
const msgText = trimInput(textToSend.getValue());
client.query(
query: gql`
query mutation($fromID: String!, $toID: String!, $msgText: String!)
createIM(fromID: $fromID, toID: $toID, msgText: $msgText)
fromID
toID
msgText
`,
variables:
fromID: fromID,
toID: toID,
msgText: msgText
,
forceFetch: false,
).then(( data ) =>
console.log('got data', data);
).catch((error) =>
console.log('there was an error sending the query', error);
);
查询变量(fromID、toID和msgText)按预期进入函数,但Apollo抛出错误:
message: "Network error: Unexpected token < in JSON at position 0"
我错过了什么?
【问题讨论】:
查看 chrome 网络选项卡 - 你能在其中看到请求吗?它命中了什么 URL,返回值是多少? 请求网址:localhost:3000/graphql。推荐人:localhost:3000/create_im/572bddac4ecbbac0ffe37fdf。请求负载:"query":"query mutation($fromID: String!, $toID: String!, $msgText: String!) \n createIM(fromID: $fromID, toID: $toID, msgText: $msgText) \n fromID\n toID\n msgText\n \n\n","variables":"fromID":"s9trFBxQcpaCjnon2","toID":"572bddac4ecbbac0ffe37fdf","msgText":"Testing 123" “操作名称”:“突变”。我在哪里可以找到返回值? 在包含引用代码的文件中,我通过import ApolloClient from 'apollo-client'; const client = new ApolloClient();
访问ApolloClient。这足以访问之前定义的解析器吗?
【参考方案1】:
请改用这个.. 您应该使用 mutate 进行突变而不是查询..
client.mutate(
mutation: gql`
mutation createIM($fromID: String!, $toID: String!, $msgText: String!)
createIM(fromID: $fromID, toID: $toID, msgText: $msgText)
fromID
toID
msgText
`,
variables:
fromID: fromID,
toID: toID,
msgText: msgText
,
forceFetch: false,
).then(( data ) =>
【讨论】:
以上是关于Apollo/GraphQL 突变在 GraphIQL 中有效,但在客户端代码中无效?的主要内容,如果未能解决你的问题,请参考以下文章
在 Angular Apollo Graphql 中访问突变结果
Apollo/graphQL:如何将乐观 UI 用于嵌套反应组件的突变?
Apollo / GraphQL / Prisma“登录”突变不会返回所有用户字段