【发布时间】:2019-03-25 01:35:10
【问题描述】:
我如下构建了一个 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');
});
我可以像下面这样从 Postman 拨打 POST 电话,
但是,当我尝试在 index.html 中加载的 app.js 文件中使用 fetch 调用 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(错误请求)
并响应错误消息:“必须提供查询字符串。”
【问题讨论】:
-
不要字符串化“body”
-
@Geert-Jan 问题不是由字符串化“body”引起的,能否请您多说一下为什么不将“body”字符串化?
标签: javascript graphql