问题
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."
回答1:
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.
来源:https://stackoverflow.com/questions/52904569/graphql-api-works-with-postman-but-failed-with-javascript-fetch