使用Unsplash API在NODEJS中的JSON输入的意外结束

发布于 2025-02-11 05:21:56 字数 3382 浏览 2 评论 0原文

当我从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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

囚你心 2025-02-18 05:21:56

诊断

您对响应的处理假设单个数据已发出提供完整响应数据的事件。

但是,这个假设是不正确的。 stream.able类,其中查询响应是一个子类实例,通过反复发射data事件来提供块中的内容。流的结尾由专用结束事件发出信号。

因此,必须首先收集响应数据并重新组装,然后再将其传递给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解析器直接在流中运行。但是,基本的代码结构(数据用于重复调用的处理程序餐饮提供了块数据,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 emitting data events. The end of a stream is signalled by a dedicated end 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.

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();
        }
   });
});

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 change

References

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文