NodeJS 节点获取收到ReadableStream,但收到不完整的响应

6tr1vspr  于 2023-02-03  发布在  Node.js
关注(0)|答案(1)|浏览(305)

i发出请求节点获取收到ReadableStream并收到不完整的响应。问题被视为ReadableStream在等待过程中未完成
请求:

static async postData(url = "") {
    // Default options are marked with *
    const response = await fetch(url, {
      method: "POST", // *GET, POST, PUT, DELETE, etc.
      mode: "same-origin", // no-cors, *cors, same-origin
      cache: "default", // *default, no-cache, reload, force-cache, only-if-cached
      credentials: "same-origin", // include, *same-origin, omit
      headers: {
        "Content-Type": "application/json",
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
      redirect: "follow", // manual, *follow, error
      referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
      //body: JSON.stringify(dados), // body data type must match "Content-Type" header
    });
    const stream = await response.body?.getReader().read();

    let jsonBuffer = Buffer.from(stream?.value!);

    let jsonString = jsonBuffer.toString("utf8");
    console.log(jsonString);
    return JSON.parse(jsonString); // parses JSON response into native JavaScript objects
  }

响应:{"retorno":{"status_processamento":"3","status":"OK","pagina":1,"numero_paginas":1,"contatos":[{"contato":{"id":"715461091","codigo":"","nome":"Fabio Moreno","fantasia":"","tipo_pessoa":"F","cpf_cnpj":"","endereco":"","numero":"","complemento":"","bairro":"Vila Medon","cep":"","cidade":"Americana","uf":"SP","email":"linkiez@gmail.com","fone":"","id_lista_preco":0,"id_vendedor":"0","nome_vendedor":"","s
错误:[1] SyntaxError: Unexpected end of JSON input [1] at JSON.parse (<anonymous>) [1] at TinyERP.postData (file:///home/linkiez/Desktop/Projetos/JCMserver3/dist/services/tinyERP.js:22:21) [1] at process.processTicksAndRejections (node:internal/process/task_queues:95:5) [1] at async aprovarOrcamento (file:///home/linkiez/Desktop/Projetos/JCMserver3/dist/controllers/orcamentoController.js:259:40) [1] nodemon --experimental-specifier-resolution=node -q dist/index.js exited with code SIGINT [0] tsc --watch exited with code SIGINT

wztqucjr

wztqucjr1#

您说过您使用的是Node.js的fetch,它旨在与Web平台的fetch兼容。
您的代码没有阅读整个响应。下面是getReader()返回的默认读取器上的read()方法的文档,没有参数:
ReadableStreamDefaultReader接口的read()方法返回一个Promise,提供对流的内部队列中的***下一个块***的访问。

  • (我强调)* 这不是完整的回应,这只是回应的第一部分。

但是代码不需要那么复杂,只需使用内置的json方法读取整个响应并从JSON解析它;参见下面的***注解:

static async postData(url = "") {
    const response = await fetch(url, {
        method: "POST",
        mode: "same-origin",
        cache: "default",
        credentials: "same-origin",
        headers: {
            "Content-Type": "application/json",
        },
        redirect: "follow",
        referrerPolicy: "no-referrer",
        // *** It seems odd that there's no `body` here, given it's a POST
        // saying that it's *sending* JSON (the `Content-Type` header above
        // says what you're *sending*, not what you're expecting back).
    });
    // *** This was missing, but it's important; `fetch` only rejects on
    // *network* errors, not HTTP errors:
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    // *** Fully read the response body and parse it from JSON:
    return await response.json();
}

Here's a post在我贫血的旧博客上,关于我上面添加的ok检查的必要性。

相关问题