我按如下所示构建了一个GraphQL服务器,
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');
});
我可以从邮递员发出POST呼叫,如下所示,
但是,当我尝试按以下方式在index.html中加载的app.js文件中调用访存API时,
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);
});
显示以下错误,
app.js:2 POST http://localhost:8081/graphql 400(错误请求)
和响应错误消息:“必须提供查询字符串。”
答案 0 :(得分:1)
应该通过在选项对象中提供headers
属性而不是header
来传递标题。
headers: {
'Content-Type': 'application/json',
},
主体的解析器必须知道请求的内容类型,才能知道如何正确地解析主体。如果没有标题,主体将最终成为一个空对象,因此req.body.query
是不确定的,这就是为什么您看到该错误的原因。