我試圖弄清楚如何在 Node JS 中使用和內置模塊的request功能(我知道第三方包裝器,但我正在嘗試自己弄清楚)。我遇到了一個問題,即來自回應的緩沖區資料在最后被部分切斷。使用 進行測驗時不會出現此問題。httphttpscURL
這是我一直在使用的代碼:
const { request: httpRequest } = require("http");
const { request: httpsRequest } = require("https");
const parseURLData = (url, init) => {
const { hostname, protocol, port: somePort, pathname, search } = new URL(url);
const port = somePort || (protocol === "https:" ? 443 : 80);
const options = { hostname, port, path: pathname search, ...init };
return [protocol, options];
};
const makeRequest = (url, init = { method: "GET" }) => {
const [protocol, options] = argumentsToOptions(url, init);
const request = protocol === "http:" ? httpRequest : httpsRequest;
return new Promise((resolve, reject) =>
request(options, (res) => {
res.on("error", reject);
resolve(res);
})
.on("error", reject)
.end()
);
};
// not using `async/await` while testing
makeRequest("https://jsonplaceholder.typicode.com/users/1/")
.then((res) =>
new Promise((resolve) =>
res.on("data", (buffer) => {
resolve(buffer.toString("utf8")); // part of data is cut off
// resolve(JSON.parse(buffer.toString()));
})
)
)
.then(console.log)
.catch(console.error);
這是預期的輸出(來自cURL):
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
這是實際輸出,由于某種原因,每次運行代碼時都會略有不同:
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"p
這個問題的正確解決方案是什么?如何從請求中獲取所有資料?
uj5u.com熱心網友回復:
只有在事件觸發時才應處理緩沖區end,否則您可能正在處理不完整的緩沖區。
makeRequest("https://jsonplaceholder.typicode.com/users/1/")
.then((res) =>
new Promise((resolve) => {
let totalBuffer = "";
res.on("data", (buffer) => {
totalBuffer = buffer.toString("utf8");
});
res.on("end", () => resolve(totalBuffer));
})
)
.then(console.log)
.catch(console.error);
當檔案超過 1mb 時,回應幾乎總是被截斷為幾部分,因此有必要使用end指示所有可用資料已由流處理的事件。
https://nodejs.org/api/http.html 查找“JSON 獲取示例”
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/418265.html
標籤:
