使用express-graphql和HTTP客户端从graphql获取数据

时间:2016-11-05 20:11:36

标签: http express fetch graphql-js apollo-server

我很难在标准的apollo graphql-server-express

上发出HTTP抓取请求

我已尝试按照graphql.org的指导无效。

为了测试这个,我使用Fusetools News Feed Example并使用标准http调用apollo-server切换fetch调用:

```

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body data-ng-app="App">

  <div ng-controller="Ctrl">
    <!-- If you just want to access first object -->
    <p>{{obj[0].desc}}</p>
        <!-- If you just want to access all objects -->
    <p ng-repeat="item in obj track by $index"> 
    {{item.intro}}  ---- {{item.desc}}
    
    </p>
  </div>

</body>

```

这个完整的代码只返回了返回的字段。

```

fetch('https://localhost:8080/graphql', {
                "method": 'POST',
                "headers": { "Content-type": "application/graphql", "Accept": "application/json"},
                "body": {"query": "{ places { id name address city }" }
            })
            .then(function(response) { return response.json; })
            .then(function(responseObject) { data.value = responseObject; });

``` 任何指导将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

要使用fetch到graphql server,在我的情况下使用的正确语法如下。谢谢,丹尼尔。

fetch('https://graphql-swapi.parseapp.com/', {
  method: 'POST',
  headers: { "Content-type": "application/json", "Accept": "application/json"},
  body: JSON.stringify({"query":"{allFilms {totalCount}}","variables":null,"operationName":null})
}).then(function(response) { return response.json(); })
.then(function(responseObject) { console.log('GOT', JSON.stringify(responseObject, null, '  ')); });