GraphQL API可与Postman一起使用,但因Javascript提取而失败

时间:2018-10-20 10:16:43

标签: javascript graphql

我按如下所示构建了一个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呼叫,如下所示,

enter image description here

但是,当我尝试按以下方式在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(错误请求)
和响应错误消息:“必须提供查询字符串。”

1 个答案:

答案 0 :(得分:1)

应该通过在选项对象中提供headers属性而不是header来传递标题。

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

主体的解析器必须知道请求的内容类型,才能知道如何正确地解析主体。如果没有标题,主体将最终成为一个空对象,因此req.body.query是不确定的,这就是为什么您看到该错误的原因。