批处理模式Graphene响应状态400“批处理请求应该接收列表”到React-Apollo请求

问题描述 投票:0回答:1

React-Apollo客户端(详见下文)对Graphene-Django GraphQL服务器的GraphQL请求错误为Status Code 400 Bad Request,并显示错误消息:

Batch requests should receive a list, but received {...

这是为什么?

建立

有一个GraphQL服务器(使用graphene-django)和一个功能正常的GraphiQL;例如

query AllMsgsApp {
    allMessages {
        id
        message
    }
}

会产生:

{
  "data": {
    "allMessages": [
      {
        "id": "TWVzc2FnZVR5cGU6MQ=="
        "message": "Some message..."
      }
    ]
  }
}

前端是React app(使用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
  }
]
graphql apollo react-apollo apollo-client
1个回答
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发送您希望从服务器获得的批量请求。

© www.soinside.com 2019 - 2024. All rights reserved.