简体   繁体   English

JSON.parse() 返回意外的输入结束

[英]JSON.parse() Returning Unexpected end of input

[`const express = require('express'); [`const express = require('express'); const app = express(); const app = express(); const https = require('https'); const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US"; const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req,res) => { res.send("Server is Running") app.get("/", (req,res) => { res.send("服务器正在运行")

https.get(url, (response) => {
    
    response.on("data", (data) => {

        const TimelineData = JSON.parse(data);
        console.log(TimelineData);
        
    })
})

}) })

app.listen(3000, ()=>console.log("Server is Running 0n 5000"));`] 1 app.listen(3000, ()=>console.log("服务器正在运行 0n 5000"));`] 1

 const express = require('express'); const app = express(); const https = require('https'); const url = "https://api.thevirustracker.com/free-api?countryTimeline=US"; app.get("/", (req,res) => { res.send("Server is Running") https.get(url, (response) => { response.on("data", (data) => { const TimelineData = JSON.parse(data); console.log(TimelineData); }) }) }) app.listen(3000, ()=>console.log("Server is Running 0n 5000"));

To deliver large data in an effective manner API send data in chunk/stream format.以有效的方式传递大数据 API 以块/流格式发送数据。 and to receive each chunk it triggers the ' data ' event and in your case, it might be possible that API sends data in chunk format.并接收每个块,它会触发“数据”事件,在您的情况下,API 可能会以块格式发送数据。 and it will not send you complete data in a single event.并且它不会在单个事件中向您发送完整的数据。

Let's assume the complete response of your API is: { name: 'bella', age: 34, count: 40138 }假设您的 API 的完整响应是: { name: 'bella', age: 34, count: 40138 }

And API send it in 2 chunks: API 分两部分发送:

  • Chunk1: { name: 'bella', age: 34, count: 4013 Chunk1: { name: 'bella', age: 34, count: 4013
  • Chunk2: 8 }块 2: 8 }

In that case Json.Parse() on Chunk1 or Chunk2 will not work and threw an exception.在这种情况下,Chunk1 或 Chunk2 上的Json.Parse()将不起作用并抛出异常。

To deal with this problem you need to listen to the ' end ' event and capture data from the' data ' and parse it in the ' end ' event.要处理这个问题你需要监听' end '事件并从' data '中捕获数据并在' end '事件中解析它。

Use the below code:使用以下代码:

 const express = require('express'); const app = express(); const https = require('https'); const url = "https://archive.org/advancedsearch.php?q=subject:google+sheets&output=json"; app.get("/", (req, res) => { res.send("Server is Running") https.get(url, (response) => { var responseData = ''; response.on("data", (dataChunk) => { responseData += dataChunk; }) response.on('end', () => { const TimelineData = JSON.parse(responseData); console.log(TimelineData); }); }).on('error', (e) => { console.error(e); }); }) app.listen(5000, () => console.log("Server is Running 0n 5000"));

The "data" event can be fired multiple times: https://nodejs.org/api/http.html#http_class_http_clientrequest “数据”事件可以多次触发: https://nodejs.org/api/http.html#http_class_http_clientrequest

You have to listen for the "end" event and concat all chunks from the "data" event togehter for the full body response.您必须监听“结束”事件并将来自“数据”事件的所有块连接在一起以获得全身响应。

const express = require('express');
const app = express();
const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req, res) => {

    res.send("Server is Running")

    https.get(url, (response) => {

        const chunks = [];

        response.on("data", (data) => {
            chunks.push(data);
        })

        response.on("end", () => {

            let size = chunks.reduce((prev, cur) => {
                return prev + cur.length;
            }, 0);

            let data = Buffer.concat(chunks, size).toString();

            console.log(JSON.parse(data))

        });

    })

})



app.listen(3000, () => console.log("Server is Running 0n 5000"));

why are you using https?为什么要使用 https? replace https with http and run it again.将 https 替换为 http 并再次运行。

const express = require('express');
const app = express();
const http = require('http');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req ,res) => {
    res.send("Server is Running")

    http.get(url, (response) => {
        
        response.on("data", (data) => {

            const TimelineData = JSON.parse(data);
            console.log(TimelineData);
            
        })
    })
})
const express = require('express')
const app = express()

const port = 3000

app.post('/', (req, res) => { 
  res.send('Hello World!")

})

app.listen(port, () => {
  console.log('server running')

})

When you run the program in nodejs, open the brower and type http://localhost:3000 .当您在 nodejs 中运行该程序时,打开浏览器并输入http://localhost:3000 The output will be.... output 将......

Listen for 'end ' the problem will be resolved听'end'问题就解决了

Try importing all the dependencies.尝试导入所有依赖项。 Importing is better than requiring because you can selectively load only the pieces you need.导入比要求更好,因为您可以有选择地只加载您需要的部分。 Also in package.json file add "type":"module" before scripts.同样在 package.json 文件中,在脚本前添加“type”:“module”。 The days of const something= require('something') are a thing of the past now because of new ESM modules.由于新的 ESM 模块,const something= require('something') 的日子已经成为过去。

import express from 'express';
import https from 'https';
const app=express();
const port=3000;

In package.json file在 package.json 文件中

"name": "restApiWithNode",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",

Read this article for clarity https://formidable.com/blog/2021/node-esm-and-exports/为了清楚起见,请阅读这篇文章https://formidable.com/blog/2021/node-esm-and-exports/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javascript JSON.parse throw意外的JSON输入错误结束 - javascript JSON.parse throw Unexpected end of JSON input error SyntaxError:JSON.parse 处的 JSON 输入意外结束(<anonymous> )</anonymous> - SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) 未捕获的语法错误:JSON.parse 处的 JSON 输入意外结束 - Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse 在JSON.parse中获取“ JSON输入意外结束” - Getting "Unexpected end of JSON input at JSON.parse 未捕获的 SyntaxError:JSON.parse 处的 JSON 输入意外结束(<anonymous> ) - Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) 未捕获的语法错误:JSON.parse 处的 JSON 输入意外结束(<anonymous> )</anonymous> - Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse(<anonymous>) JSON.parse 处的 JSON 输入意外结束(<anonymous> )</anonymous> - Unexpected end of JSON input at JSON.parse (<anonymous>) 语法错误:JSON.parse 处的 JSON 输入意外结束(<anonymous> ) on(&quot;数据&quot;) - SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) on("data") JAVASCRIPT JSON.parse() 返回 JSON 输入的意外结束 - JAVASCRIPT JSON.parse() return Unexpected end of JSON input 未捕获的语法错误:JSON 输入的意外结束:在 JSON.parse(<anonymous> )</anonymous> - Uncaught SyntaxError: Unexpected end of JSON input : at JSON.parse (<anonymous>)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM