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

32👍

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.

16👍

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.

👤Renzo

4👍

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

👤cpit

3👍

For sure the mutation is not formatted correctly if that is exactly what you are sending. You need an opening bracket in the mutation

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

With any of these queries when i run into bugs i paste it into either graphiql or graphql playground to identify what the formatting errors is in order to isolate what is wrong.

👤Austio

0👍

For people using laravel for backend, this helped me solve the problem

In the laravel project find file config/cors.php and change line 'paths' => ['api/*', 'sanctum/csrf-cookie'], to 'paths' => ['api/*', 'graphql', 'sanctum/csrf-cookie'],

Also in your vue app ensure that you’re not using the no-cors mode in apollo config

Regards

0👍

For me, query field name is wrong in schema.

👤stalin

Leave a comment