使用Unsplash API在NODEJS中的JSON输入的意外结束
当我从API恢复数据时,我正在使用nodejs中的Unplash 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...
我尝试的 我尝试先将数据转换为字符串然后解析,但错误是相同的
i am using unsplash api in Nodejs when i recive data from API I try to parse the data but i am getting the error unexpected end of json.
code:
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}`));
============================================================
error:
[enter image description here][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...
what I tried
I tried to convert the data into string first then parse it but the error was the same
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
诊断
您对响应的处理假设单个
数据
已发出提供完整响应数据的事件。但是,这个假设是不正确的。
stream.able
类,其中查询响应是一个子类实例,通过反复发射data
事件来提供块中的内容。流的结尾由专用结束
事件发出信号。因此,必须首先收集响应数据并重新组装,然后再将其传递给JSON解析器。
代码
警告:此代码未经测试。
注意
周围可能有JSON解析器直接在流中运行。但是,基本的代码结构(
数据
用于重复调用的处理程序餐饮提供了块数据,end
处理程序启动下一个处理步骤)不会更改参考
node.js(v18.4.0)stream.able文档: https://nodejs.org/dist/latest-v18.x/docs/api/stream.html#class-streamreamreadable docs。可以通过更换上面链接中的主要版本编号来找到其他版本的node.js的文档(但是,您观察到的效果没有改变的基本机制)
Diagnosis
Your handling of the response assumes that a single
data
event is fired that provides the complete response data.However, this assumption would be incorrect. The
stream.Readable
class, of which the query response is a subclass instance, delivers content in chunks by repeatedly emittingdata
events. The end of a stream is signalled by a dedicatedend
event.In consequence, response data first has to be collected and reassembled before passing it on to the JSON parser.
Code
Warning: This code is untested.
Note
There might be JSON parsers around that directly operate on streams. However, the basic code structure (
data
handler catering for repeated calls providing chunks of data,end
handler to initiate next processing steps) wouldn't changeReferences
The node.js (v18.4.0) stream.Readable docs: https://nodejs.org/dist/latest-v18.x/docs/api/stream.html#class-streamreadable docs. Docs for other versions of node.js can be found by replacing the major version number in the link above (the basic mechanism underlying the effect you observed has not changed though)