React Native Apollo 客户端 GraphQL Mutation returns 400 错误

React Native Apollo client GraphQL Mutation returns 400 error

我在我的 React Native 应用程序上使用 GraphQL 和 Apollo,我的查询 运行 没问题,但是当我尝试 运行 一个突变(使用完全相同的代码在浏览器上),我收到以下错误:

Error: Network error: Response not successful: Received status code 400
    at new ApolloError (bundle.umd.js:76)
    at bundle.umd.js:952
    at bundle.umd.js:1333
    at Array.forEach (<anonymous>)
    at bundle.umd.js:1332
    at Map.forEach (<anonymous>)
    at QueryManager.broadcastQueries (bundle.umd.js:1327)
    at bundle.umd.js:901
    at tryCallOne (core.js:37)
    at core.js:123

以下是我尝试发送此突变的方式:

const createItem = gql`{
  mutation {
    createItem(title: "Banana", summary: "Santa", campaignId: 1, pinId: 1) {
      id
    }
  }
}`;

client.query({query: createItem}).then((resp) => {
  console.log('query answer');
  console.log(resp);
}).catch((error) => {
  console.log('error');
  console.log(error);
});

这是我的客户:

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

let bearer_token = '';

const httpLink = new HttpLink({ uri: 'http://localhost:3000/graphql/' });

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = bearer_token;
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${bearer_token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

export function setToken(token) {
  bearer_token = token;
}

export default client;

在后端,我调试并收到请求,它根据客户端设置的令牌找到用户,但随后什么都不做,returns 我再次收到 400,仅当我尝试从应用程序发送它,在它工作的 graphiql 浏览器上。

我错过了什么?非常感谢。

正如丹尼尔指出的那样,我的 gql 有一个额外的括号,但这不是问题,我实际上应该使用 mutate 函数而不是 query。该文档显示了带有 query 的示例,但我没有找到任何带有 mutate 的示例,因此造成了混淆。

const createItem = gql`
mutation {
  createItem(title: "Banana", summary: "Santa", campaignId: 1, pinId: 1) {
    id
  }
}`;

并使用它:

client.mutate({mutation: createItem}).then((resp) => {
  console.log(resp)
}).catch((error) => {
  console.log(error)
});

希望这对其他 GraphQL 初学者有所帮助!