JS 使用 HTTP 批量获取数据

JS Fetching batch data with HTTP

我的 RESTful 服务允许 batching requests

我正在尝试在 Fetch API 的帮助下将请求合并为一批:

let req1 = {
        url: "/cups/count",
        options: {
           method: 'GET',
           headers: {
               'Content-Type': 'application/http'
           }
       }
    },

    req2 = {
        url: "/spoons/count",
        options: {
           method: 'GET',
           headers: {
               'Content-Type': 'application/http'
           }
        }
    },
    authToken = "Bearer my_token123",
    batchUrl = "http://something.com/batch",
    options = {
        method: 'POST',
        headers: {
            'Authorization': authToken,
            'Content-Type': 'multipart/mixed'
        },
        body: {req1, req2}
    };

    return fetch(batchUrl, options)
        .then(response => response.json())
        .then(items => dispatch(batchSuccess(items)))
        .catch((err) => {
            console.log(err)
        });

但是 returns 一个错误 - 错误的请求。我想我可能以错误的方式组合了 HTTP 请求。

有更简单的方法吗?

我可以在网络 Chrome 开发工具的哪个位置看到嵌套的 HTTP 请求?

您的代码不起作用,因为它不遵循 multipart/mixed 请求格式:

  1. Content-Type头中,没有边界信息。
  2. 子请求不按边界划分,而是作为 req1 和 req2 对象的纯文本发送。

为了发送有效的 multipart/mixed 请求,有一个 node.js 模块 batchelor。从介绍页面来看,它的用法还是很简单的。

如果你想从浏览器发送multipart/mixed请求,你可以使用构建工具(gulp、webpack等)将batchelor编译成类似"batchelor-compiled.js"的东西并导入它HTML.

对于开发人员工具,我在 Chrome 中没有找到任何内容,但在 Firefox 调试 window 的 "Params" 选项卡中可以看到子请求。

这是使用 Fetch API with the Gmail Batch REST API.

的批处理请求示例

这将一次获取多条消息的内容。

const response = await fetch("https://www.googleapis.com/batch/gmail/v1", {
  headers: {
    "Content-Type": "multipart/mixed; boundary=batch_boundary",
    Authorization: "Bearer <access_token>",
  },
  method: "POST",
  body: `--batch_boundary
Content-Type: application/http
Content-ID: 1

GET /gmail/v1/users/me/messages/{message-id-1}

--batch_boundary
Content-Type: application/http
Content-ID: 2

GET /gmail/v1/users/me/messages/{message-id-2}

--batch_boundary--`,
});

console.log(await response.text());