React Native Apollo客户端GraphQL Mutation返回400错误

时间:2018-03-16 20:57:17

标签: javascript react-native graphql apollo mutation

我在我的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;

在后端,我调试并收到请求,它根据客户端上设置的令牌找到用户,但后来什么也没做,只返回我,只有当我尝试从应用程序,在graphiql浏览器上运行。

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

1 个答案:

答案 0 :(得分:0)

正如丹尼尔指出的那样,我的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初学者!