【问题标题】:GraphQL API works with Postman, but failed with Javascript fetchGraphQL API 可与 Postman 一起使用,但无法使用 Javascript 获取
【发布时间】: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


【解决方案1】:

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

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

请求的内容类型是body-parser 知道如何正确解析body 所必需的。如果没有标头,body 会以一个空对象结束,因此 req.body.query 是未定义的,这就是您看到该错误的原因。

【讨论】:

  • 感谢您的明确解释,它对我有用。
猜你喜欢
  • 1970-01-01
  • 2019-03-31
  • 2020-11-02
  • 2017-10-15
  • 2021-12-17
  • 2017-10-13
  • 2019-01-04
  • 2021-12-04
  • 2018-03-17
相关资源
最近更新 更多