Skip to content
Advertisement

Node Fetch Post Request using Graphql Query

I’m trying to make a POST request with a GraphQL query, but it’s returning the error Must provide query string, even though my request works in PostMan.

Here is how I have it running in PostMan:

enter image description here

enter image description here

And here is the code I’m running in my application:

const url = `http://localhost:3000/graphql`;    
return fetch(url, { 
  method: 'POST',
  Accept: 'api_version=2',
  'Content-Type': 'application/graphql',
  body: `
    {
      users(name: "Thomas") { 
        firstName
        lastName 
      } 
    }
  `
})
.then(response => response.json())
.then(data => {
  console.log('Here is the data: ', data);
  ...
});

Any ideas what I’m doing wrong? Is it possible to make it so that the body attribute I’m passing in with the fetch request is formatted as Text like I’ve specified in the PostMan request’s body?

Advertisement

Answer

The body is expected to have a query property, containing the query string. Another variable property can be passed as well, to submit GraphQL variables for the query as well.

This should work in your case:

const url = `http://localhost:3000/graphql`;
const query = `
  {
    users(name: "Thomas") { 
      firstName
      lastName 
    } 
  }
 `

return fetch(url, { 
  method: 'POST',
  Header: {
     'Content-Type': 'application/graphql'
  }
  body: query
})
.then(response => response.json())
.then(data => {
  console.log('Here is the data: ', data);
  ...
});

This is how to submit GraphQL variables:

const query = `
  query movies($first: Int!) {
    allMovies(first: $first) {
      title
    }
  }
`

const variables = {
  first: 3
}

return fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({query, variables})
})
.then(response => response.json())
.then(data => {
  return data
})
.catch((e) => {
  console.log(e)
})

I created a complete example on GitHub.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement