如何正确解码原始数据响应

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

我正在尝试使用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个回答
0
投票

你不能使用response.text()response.json()而不是response.arrayBuffer()

fetch('https://httpbin.org/get')
  .then(response => response.json())
  .then(console.log);
© www.soinside.com 2019 - 2024. All rights reserved.