【问题标题】:How to properly decode raw data response如何正确解码原始数据响应
【发布时间】:2019-03-22 23:07:28
【问题描述】:

我正在尝试使用 API(没有文档),后端使用 ScalaJS 和 uPickle (MsgPack),它为每个 API 端点返回原始二进制数据。我需要以某种方式将这些原始二进制数据转换为可读的 JSON。

这是我的代码:

function arrayBufferToString( buffer, encoding, callback ) {
    var blob = new Blob([buffer],{type:'text/plain'});
    var reader = new FileReader();
    reader.onload = function(evt){callback(evt.target.result);};
    reader.readAsText(blob, encoding);
}
fetch("https://example.com/example/fetchStats", {
    "credentials": "include",
    "headers": {
        "accept": "*/*",
        "accept-language": "en-US,en;q=0.9",
        "content-type": "application/octet-stream"
    },
    "body":"\u0000",
    "method":"POST",
    "mode":"cors"
}).then(response => response.arrayBuffer().then(arrayBuffer => {
    if (arrayBuffer) {
        var bytes = new Uint8Array(arrayBuffer);
        var u16 = new Uint16Array(bytes.length)
        for(var i=0;i<bytes.length;i++){
            u16[i] = bytes[i].toString().charCodeAt(0)
        }
        arrayBufferToString(u16, 'UTF-8', console.log.bind(console))

    }
}));

这将返回以下字符串:“3011102010301”(数字之间有空格) 我不确定如何读取这些数据。就像我上面说的,API 使用 https://github.com/lihaoyi/upickle 代替 JSON。

有人知道如何将原始二进制数据转换为人类可读的格式吗?

上面的 HTTP 请求将返回的示例:╚ ╔t╔ ╗ ╔ ╚ ╔

我很迷茫。

【问题讨论】:

    标签: javascript api encoding msgpack


    【解决方案1】:

    你不能用response.text()response.json() 代替response.arrayBuffer()

    fetch('https://httpbin.org/get')
      .then(response => response.json())
      .then(console.log);

    【讨论】:

      猜你喜欢
      • 2012-07-04
      • 2019-11-09
      • 2022-01-05
      • 1970-01-01
      • 2021-05-30
      • 2020-03-07
      • 1970-01-01
      • 2019-06-15
      • 2018-12-14
      相关资源
      最近更新 更多