當我從 API 接收資料時,我在 Nodejs 中使用 unsplash api 我嘗試決議資料,但我收到錯誤意外結束 json。
代碼:
const express = require("express");
const https = require("https");
const app = express();
const port = 4000;
// app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
app.set("view engine", "ejs");
app.get("/", (req, res) => {
const url ="https://api.unsplash.com/photos/?client_id=ipLjiRmWcJ-jWn5uG8UhibNGiFgHxTVE_KeHHb8Oo3M";
https.get(url, (response) => {
status_code = response.statusCode;
if (status_code == 200) {
try {
response.on("data", (data) => {
var data_str = data.toString();
console.log(JSON.parse(data_str));
});
} catch (error) {
console.log(error);
}
res.send();
}
});
});
app.listen(port, () => console.log(`connected to port: ${port}`));
==================================================== ==========
錯誤: [在此處輸入影像描述][1]
undefined:1
[{"id":"3f04FMm_Jqk","created_at":"2022-03-31T10:33:43-04:00","updated_at":"2022-06-25T17:25:36-04:00","promoted_at":null,"width":6048,"height":4024,"color":"#8c8c73","blur_hash":"LLE2nHWB0KVse.ozIoxaM{i_s:S4","description":null,"alt_description":null,"urls":{"raw":"https://images.unsplash.com/photo-1648737119359-510d4f551382?ixid=MnwzNDEyNDR8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1NjI2NjU2OQ\u0026ixlib=rb-1.2.1","full":"https://images.unsplash.com/photo-1648737119359-510d4f551382?crop=entropy\u0026cs=tinysrgb\u0026fm=jpg\u0026ixid=MnwzNDEyNDR8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1NjI2NjU2OQ\u0026ixlib=rb-1.2.1\u0026q=80","regular":"https://images.unsplash.com/photo-1648737119359-510d4f551382?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDEyNDR8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1NjI2NjU2OQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=1080","small":"https://images.unsplash.com/photo-1648737119359-510d4f551382?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDEyNDR8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1NjI2NjU2OQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=400","thumb":"https://images.unsplash.com/photo-1648737119359-510d4f551382?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDEyNDR8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1NjI2NjU2OQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=200","small_s3":"https://s3.us-west-2.amazonaws.com/images.unsplash.com/small/pho
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (C:\Users\Muslim Shah\Documents\express\unsplash\app.js:19:28)
at IncomingMessage.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at IncomingMessage.Readable.push (node:internal/streams/readable:228:10)
at HTTPParser.parserOnBody (node:_http_common:141:24)
at TLSSocket.socketOnData (node:_http_client:494:22)
at TLSSocket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
[nodemon] app crashed - waiting for file changes before starting...
我嘗試了什么我嘗試 先將資料轉換為字串然后決議它,但錯誤是一樣的
uj5u.com熱心網友回復:
診斷
您對回應的處理假定data觸發了提供完整回應資料的單個事件。
但是,這種假設是不正確的。stream.Readable查詢回應是子類實體的類通過重復發出事件以塊的形式傳遞內容data。流的結束由專用end事件發出信號。
因此,在將回應資料傳遞給 JSON 決議器之前,必須首先收集和重組回應資料。
代碼
警告:此代碼未經測驗。
const express = require("express");
const https = require("https");
const app = express();
const port = 4000;
// app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
app.set("view engine", "ejs");
app.get("/", (req, res) => {
const url ="https://api.unsplash.com/photos/?client_id=ipLjiRmWcJ-jWn5uG8UhibNGiFgHxTVE_KeHHb8Oo3M";
https.get(url, (response) => {
status_code = response.statusCode;
if (status_code == 200) {
// Watch out here:
// - Response data is delivered in chunks
// - If your next processing step operates on the whole response data, you need to collect the chunks into one string first.
// - Your dat ais ready for further processing when the `end` event is received.
//
let data_complete = ''
;
try {
response.on("data", (data_chunk) => {
data_complete = data_chunk.toString();
});
response.on("end", () => {
console.log(JSON.parse(data_complete));
});
} catch (error) {
console.log(error);
}
res.send();
}
});
});
筆記
周圍可能有直接對流進行操作的 JSON 決議器。然而,基本的代碼結構(data處理重復呼叫提供資料塊,end處理程式啟動下一個處理步驟)不會改變
參考
node.js (v18.4.0) stream.Readable 檔案:https ://nodejs.org/dist/latest-v18.x/docs/api/stream.html#class-streamreadable檔案。通過替換上面鏈接中的主要版本號可以找到其他版本的 node.js 的檔案(盡管您觀察到的效果的基本機制沒有改變)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/495937.html
下一篇:ReduxToolkitQuery中的updateQueryData()和patchQueryData()有什么區別?
