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
1条答案
按热度按时间wztqucjr1#
您说过您使用的是Node.js的
fetch
,它旨在与Web平台的fetch
兼容。您的代码没有阅读整个响应。下面是
getReader()
返回的默认读取器上的read()
方法的文档,没有参数:ReadableStreamDefaultReader
接口的read()
方法返回一个Promise
,提供对流的内部队列中的***下一个块***的访问。但是代码不需要那么复杂,只需使用内置的
json
方法读取整个响应并从JSON解析它;参见下面的***
注解:Here's a post在我贫血的旧博客上,关于我上面添加的
ok
检查的必要性。