Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo-client returns "400 (Bad Request) Error" on sending mutation to server

I am currently using the vue-apollo package for Apollo client with VueJs stack with django and graphene-python for my GraphQl API.

I have a simple setup with vue-apollo below:

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)

I also have CORS setup on my Django settings.py with the django-cors-headers package. All queries and mutations resolve fine when I use graphiQL or the Insomnia API client for chrome, but trying the mutation below from my vue app:

'''

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: "[email protected]",
          password: "pa$$word",
          username: "testuser"
        }
      }).then(data => {
          console.log(result)
      })
    }
  }
};

NewUser.gql

mutation createUser($email: String!, $password: String!, $username: String!) {
  createUser (username: $name, password: $password, email: $email)
  user {
    id
    username
    email
    password
  }
}

returns with the error response below:

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

Regular queries in my vue app, however, work fine resolving the right response, except mutations, so this has me really baffled

like image 595
Feyisayo Sonubi Avatar asked Sep 09 '18 19:09

Feyisayo Sonubi


People also ask

How do you update the Apollo Client cache after a mutation?

If a mutation updates a single existing entity, Apollo Client can automatically update that entity's value in its cache when the mutation returns. To do so, the mutation must return the id of the modified entity, along with the values of the fields that were modified.

What is mutation in Apollo Client?

The useMutation React hook is the primary API for executing mutations in an Apollo application. To execute a mutation, you first call useMutation within a React component and pass it the mutation you want to execute, like so: JavaScript. my-component.jsx.

How do I clear the Apollo cache in my browser?

When we have access to the cache object we can call cache. data. delete(key) where key is the key that Apollo is using to store the data for a specific item. And the record will be entirely deleted from the cache.

How do you handle errors in GraphQL?

To add errors to your data, you need to use the Union type (a.k.a. Result ) in your GraphQL schema. Also, the logic in the resolver is rewritten so that next to the result or error for the operation you also need to return a type for it.


Video Answer


3 Answers

400 errors generally mean there's something off with the query itself. In this instance, you've defined (and you're passing in) a variable called $username -- however, your query references it as $name on line 2.

like image 92
Daniel Rearden Avatar answered Oct 23 '22 05:10

Daniel Rearden


In addition to graphiQL, I would like to add that apollo-link-error package would also had been of great help. By importing its error handler { onError }, you can obtain great detail through the console about errors produced at network and application(graphql) level :

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,
  ...
});

By adding this configuration where you instantiate your Apollo Client, you would have obtained an error similar to this one:

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

Further information can be found in Apollo Doc - Error handling: https://www.apollographql.com/docs/react/features/error-handling. Hope it helps in the future.

like image 26
Renzo Avatar answered Oct 23 '22 05:10

Renzo


For me, it was the fact that I was using a field not defined in the GraphQL schema. Always be careful!

like image 4
cpit Avatar answered Oct 23 '22 06:10

cpit