Apollo客户端在向服务器发送突变时返回“ 400(错误请求)错误”

Fey*_*ubi 2 django apollo vue.js graphql graphene-python

我目前正在为Apollo客户端使用vue-apollo包,并为我的GraphQl API使用带有django和graphene-python的VueJs堆栈。

我在下面用vue-apollo进行了简单的设置:

import Vue from 'vue'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo'
import Cookies from 'js-cookie'


const httpLink = new HttpLink({
  credentials: 'same-origin',
  uri: 'http://localhost:8000/api/',
})

// Create the apollo client
const apolloClient = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
  connectToDevTools: true,
})

export const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
})

// Install the vue plugin
Vue.use(VueApollo)
Run Code Online (Sandbox Code Playgroud)

我还settings.py使用django-cors-headers软件包在Django 上设置了CORS 。当我将graphiQL或Insomnia API客户端用于chrome时,所有查询和突变都可以很好地解决,但是可以从vue应用尝试以下突变:

'''

import gql from "graphql-tag";
import CREATE_USER from "@/graphql/NewUser.gql";

export default {
  data() {
    return {
      test: ""
    };
  },
  methods: {
    authenticateUser() {
      this.$apollo.mutate({
        mutation: CREATE_USER,
        variables: {
          email: "test@example.com",
          password: "pa$$word",
          username: "testuser"
        }
      }).then(data => {
          console.log(result)
      })
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

NewUser.gql

mutation createUser($email: String!, $password: String!, $username: String!) {
  createUser (username: $name, password: $password, email: $email)
  user {
    id
    username
    email
    password
  }
}
Run Code Online (Sandbox Code Playgroud)

返回以下错误响应:

POST http://localhost:8000/api/ 400 (Bad Request)

ApolloError.js?d4ec:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400
Run Code Online (Sandbox Code Playgroud)

但是,在vue应用中的常规查询可以很好地解决正确的响应(变异除外),因此这让我感到困惑

小智 12

除了 graphiQL,我想补充一点, apollo-link-error 包也有很大帮助。通过导入其错误处理程序 { onError },您可以通过控制台获取有关网络和应用程序(graphql)级别产生的错误的详细信息:

import { onError } from 'apollo-link-error';
import { ApolloLink } from 'apollo-link';

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    console.log('graphQLErrors', graphQLErrors);
  }
  if (networkError) {
    console.log('networkError', networkError);
  }
});

const httpLink = ...

const link = ApolloLink.from([errorLink, httpLink]);

const client = new ApolloClient({
  ...,
  link,
  ...
});
Run Code Online (Sandbox Code Playgroud)

通过在实例化 Apollo 客户端的位置添加此配置,您将获得与此类似的错误:

GraphQLError{message: "Syntax Error: Expected {, found Name "createUser""}

更多信息可以在 Apollo Doc - 错误处理中找到:https : //www.apollographql.com/docs/react/features/error-handling。希望它在未来有所帮助。


Dan*_*den 8

通常有400个错误表示查询本身存在问题。在这种情况下,您已经定义(并且正在传递)一个名为的变量$username-但是,您的查询$name在第2行中引用了该变量。