Getter Jetter
Getter Jetter

Reputation: 2081

GraphQl client query/mutation not working ( vanilla js )

So I just started using GraphQl yesterday and I'm a little bit confused about how to pass my queries from the client.

What I want:

I just want to query/mutate with a simple fetch:

const mutation = `
  // even better would be: UserRegister( firstName: ${firsName}, lastName: ${lastName}, email: ${email}, password: ${password} )
  UserRegister( firstName: "John", lastName: "Doe", email: "[email protected]", password: "123" ) {
    _id,
    firstName,
    lastName,
    email
  }
`

const options = {
  'method': 'POST',
  'headers': { 'Content-Type': 'application/json' },
  'body': JSON.stringify( { mutation } )
}

const res = await fetch( 'http://localhost:3000/graphql', options )

Now when running this from the client I get an http://localhost:3000/graphql 400 (Bad Request) error.

But when I run the same query with the playground it works just fine:

enter image description here

What am I doing wrong here?


Working query (not answer to my question):

I managed to get my query working with Apollo client, but I have the feeling that this is a lot of code just for a query. When using Apollo client is there a way to write the query with less code? Why do I need to define the variable types here when they're already defined in the schema on the server (couldn't the server do the validation)?

const client = new ApolloClient( {
  'uri': 'http://localhost:3000/graphql',
  'cache': new InMemoryCache()
} )

const mutation = gql`
  // why this?
  mutation UserRegister( $firstName: String!, $lastName: String!, $email: String!, $password: String! ) {
    UserRegister( firstName: $firstName, lastName: $lastName, email: $email, password: $password ) {
      _id,
      firstName,
      lastName,
      email
    }
  }
`

const res = await client.mutate( {
  mutation,
  // also why defining the variables here?
  'variables': {
    'firstName': 'John',
    'lastName': 'Doe',
    'email': '[email protected]',
    'password': '123'
  }
} )

Upvotes: 0

Views: 1486

Answers (1)

Getter Jetter
Getter Jetter

Reputation: 2081

@xadm pointed me to the solution:

const query = `
  mutation {
    UserRegister( firstName: "John", lastName: "Doe", email: "[email protected]", password: "123" ) {
      _id,
      firstName,
      lastName,
      email
    }
  }
`

const options = {
  'method': 'POST',
  'headers': { 'Content-Type': 'application/json' },
  'body': JSON.stringify( { query } )
}

const res = await fetch( 'http://localhost:3000/graphql', options )

Upvotes: 1

Related Questions