React-Apollo客户端(详见下文)对Graphene-Django GraphQL服务器的GraphQL请求错误为Status Code 400 Bad Request
,并显示错误消息:
Batch requests should receive a list, but received {...
为什么?
设置
使用功能正常的Graph i QL获得GraphQL服务器(使用graphene-django);例如
query AllMsgsApp {
allMessages {
id
message
}
}
将产生:
{
"data": {
"allMessages": [
{
"id": "TWVzc2FnZVR5cGU6MQ=="
"message": "Some message..."
}
]
}
}
前端是React应用(使用create-react-app)和apollo-client等等。
App.js
中的我的测试代码段是:
import React, { Component } from 'react'
import { ApolloClient, InMemoryCache } from 'apollo-client-preset';
import { ApolloProvider } from 'react-apollo';
import { createHttpLink } from 'apollo-link-http';
import gql from 'graphql-tag'
const client = new ApolloClient({
link: createHttpLink({
uri: 'http://localhost:8000/gql/' }),
cache: new InMemoryCache(),
});
client.query({
query: gql`
query AllMsgsApp {
allMessages {
id
message
}
}
`
}).then(response => console.log(response.data.allMessages))
yarn start
后,获得的回复为400 Bad Request
:
{"errors":[{"message":"Batch requests should receive a list, but received {'operationName': 'AllMsgsApp', 'variables': {}, 'query': 'query AllMsgsApp {
allMessages {
id
message
__typename
}
}
'}."}]}
依赖关系
"dependencies": {
"apollo-cache-inmemory": "^1.1.4",
"apollo-client": "^2.0.4",
"apollo-client-preset": "^1.0.5",
"apollo-link-http": "^1.3.1",
"graphql": "^0.12.0",
"graphql-tag": "^2.6.0",
"react": "^16.2.0",
"react-apollo": "^2.0.4",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2",
"react-scripts": "1.0.17"
}
附加
顺便说一句,以下内容:
curl -X POST -H "Content-Type: application/json" -d '{"query": "{ allMessages { id, message } }"}' http://localhost:8000/gql
基本上会返回相同的错误:
{"errors":[{"message":"Batch requests should receive a list, but received {'query': '{ allMessages { id, message } }'}."}]}
然而,这个会返回预期的结果(请注意封闭的[ ]
):
curl -X POST -H "Content-Type: application/json" -d '[{"query": "{ allMessages { id, message } }"}]' http://localhost:8000/gql
是:
[
{
"data":{
"allMessages":[
{
"id":"TWVzc2FnZVR5cGU6MQ==",
"message":"Some message..."
}
]
},
"id":null,
"status":200
}
]
答案 0 :(得分:3)
而不是使用createHttpLink
使用较新的BatchHttpLink
。
像这样导入:
import { BatchHttpLink } from "apollo-link-batch-http";
和
const client = new ApolloClient({
link: new BatchHttpLink({
uri: 'http://localhost:8000/gql/' }),
cache: new InMemoryCache(),
});
我希望这会有所帮助。这将从您的服务器发送Apollo的批量请求。