简体   繁体   中英

GraphQL API works with Postman, but failed with Javascript fetch

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,

在此处输入图片说明

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."

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM