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

标签 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;

在后端,我调试并收到请求,它根据在客户端设置的 token 找到用户,但随后什么都不做并再次返回 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 初学者有所帮助!

关于javascript - React Native Apollo 客户端 GraphQL Mutation 返回 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49329386/

相关文章:

javascript - 使用 NightmareJS 模拟内置对象

graphql - Gatsby 在 graphql 获取时的构建过程中给出错误 "Error: Type with name "File"does not exists"

javascript - 如何在 forEach 中运行 useQuery?

javascript - 如何实现赞成票和反对票?

javascript - jQuery 使图像变大

javascript - 将变量 i 传递给 D3 函数

rust - 是否可以使用 Tokio 和 Juniper 在 GraphQL 对象字段中执行任何类型的并行计算?

react-native - 如何从 stack.navigation 之外的组件使用 navigation.navigate

android - 无法在 react-native 的默认 WebView 上播放 hls

php - 尝试将 api 与 native react 连接起来