Node Fetch Post Request using Graphql Query Node Fetch Post Request using Graphql Query express express

Node Fetch Post Request using Graphql Query


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',  Accept: 'api_version=2',  'Content-Type': 'application/graphql',  body: JSON.stringify({ 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.