【问题标题】:JS Fetching batch data with HTTPJS 使用 HTTP 获取批量数据
【发布时间】:2017-08-28 23:42:38
【问题描述】:

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

但是它返回错误 - 错误请求。我想我可能会以错误的方式组合 HTTP 请求。

有没有更简单的方法?

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

【问题讨论】:

    标签: javascript http google-chrome-devtools fetch-api


    【解决方案1】:

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

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

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

    如果您想从浏览器发送multipart/mixed 请求,您可以使用构建工具(gulp、webpack 等)将batchelor 编译为“batchelor-compiled.js”之类的内容并以HTML 格式导入。

    对于开发者工具,我在 Chrome 中没有找到任何东西,但子请求在 Firefox 调试窗口的“参数”选项卡中可见。

    【讨论】:

      【解决方案2】:

      这是一个使用Fetch APIGmail 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());
      

      【讨论】:

      • 请注意,授权标头有错字:应该是Authorization: "Bearer &lt;access_token&gt;"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多