【问题标题】:React Native Apollo client GraphQL Mutation returns 400 errorReact Native Apollo 客户端 GraphQL Mutation 返回 400 错误
【发布时间】:2018-08-26 00:44:36
【问题描述】:

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

在后端,我进行了调试并收到了请求,它根据客户端上设置的令牌找到用户,但随后什么也不做,再次返回 400,只有当我尝试从该应用程序,它可以在 graphiql 浏览器上运行。

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

【问题讨论】:

    标签: javascript react-native graphql apollo mutation


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 2021-05-30
      • 2019-06-12
      • 2022-12-12
      • 2019-01-04
      • 2021-10-12
      • 2019-01-26
      • 2019-06-25
      • 1970-01-01
      相关资源
      最近更新 更多