GraphQL API可与Postman一起使用,但因Javascript提取而失败 [英] GraphQL API works with Postman, but failed with Javascript fetch

查看:64
本文介绍了GraphQL API可与Postman一起使用,但因Javascript提取而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如下构建了一个GraphQL服务器,

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');
});

我可以从邮递员发出POST呼叫,如下所示,

And I can make a POST call from Postman like below,

但是,当我尝试按如下方式在index.html中加载的app.js文件中通过访存调用API时,

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);
});

它显示以下错误,
app.js:2 POST http://localhost:8081/graphql 400(错误请求)
和响应错误消息:必须提供查询字符串."

It says the following errors,
app.js:2 POST http://localhost:8081/graphql 400 (Bad Request)
and response error message: "Must provide query string."

推荐答案

应该通过在options对象(而不是 header )中提供 headers 属性来传递标题.

Headers should be passed in by providing a headers property in the options object, not header.

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

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

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.

这篇关于GraphQL API可与Postman一起使用,但因Javascript提取而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆