1
votes

I built a GraphQL server as follows,

import express from 'express';
import graphqlHTTP from 'express-graphql';
import { schema } from './data/schema';

const app = express();

app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
  res.sendFile('index.html');
});

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}));

app.listen(8081, () => {
  console.log('Running server on port localhost:8081/graphql');
});

And I can make a POST call from Postman like below,

enter image description here

However, when I try to call the API with fetch in the app.js file which is loaded in the index.html as follows,

function fetchQuery(query) {
  return fetch('/graphql', {
    method: 'POST',
    header: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ query })
  }).then(response => {
    return response.json();
  });
}
const query = `{
  friend {
    firstName
  }
}`;

fetchQuery(query).then((data) => {
  console.log(data);
});

It says the following errors,
app.js:2 POST http://localhost:8081/graphql 400 (Bad Request)
and response error message: "Must provide query string."

1
Don’t stringify the ‘body’Geert-Jan
@Geert-Jan The issue is not caused by stringifying the 'body', could you please say more about why not stringify the 'body'?Lenient Liu

1 Answers

1
votes

Headers should be passed in by providing a headers property in the options object, not header.

headers: {
  'Content-Type': 'application/json',
},

The content type for the request is necessary for body-parser to know how to correctly parse the body. Without the header, body ends up an empty object and therefore req.body.query is undefined, which is why you see that error.