Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
Thomas Avatar asked Jun 17 '17 23:06

Thomas


People also ask

Can GraphQL be used for POST?

HTTP Methods, Headers, and BodyYour GraphQL HTTP server should handle the HTTP GET and POST methods.

How do I get data from a GraphQL query?

In GraphQL, you fetch data with the help of queries. A query is a GraphQL Operation that allows you to retrieve specific data from the server. We ask the server for all the todos and their titles in the above query. The “ todos " represents an object and " title " a field.


1 Answers

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.

like image 119
marktani Avatar answered Sep 25 '22 01:09

marktani