简体   繁体   English

当 JSON 有效时,JSON 输入意外结束

[英]Unexpected end of JSON input when JSON is valid

I am using express to get data from a public API and use the data in my front end.我正在使用 express 从公共 API 获取数据并在我的前端使用数据。

This is my characters route which works fine on certain Public API URLs, but most that I try ends up in an unexpected end of input error.这是我的字符路由,它在某些公共 API URL 上运行良好,但我尝试的大多数都以意外的输入错误结束而告终。

I am also getting an Unexpected token, in JSON at position 48 .我还在Unexpected token, in JSON at position 48 How can this happen when it appears to be valid JSON?当它看起来是有效的 JSON 时怎么会发生这种情况?

const express = require('express'); // Web Framework
const https = require('https');
const router = express.Router();

const api = 'https://www.cheapshark.com/api/1.0/games?title=batman&steamAppID=35140&limit=60&exact=0';

router.get("/", function(req, res) {
    https.get(api, (response) => {
        console.log(response.statusCode);
        
        response.on('data', (d) => {
            try{
            const data = JSON.parse(d);
            console.log(data);
            res.send(data);
            } catch (err) {
                console.log(err);
            }
        })

        // res.send("Running")
    })
})

module.exports = router;

This is my index.js which uses the character route这是我使用字符路由的 index.js

const express = require('express'); // Web Framework
const app = express();
const PORT = 3000;

const charactersRoute = require('./routes/characters');


//Characters Route
app.use('/characters', charactersRoute)

app.listen(PORT, function(err) {
    if(err) console.log(err);
    console.log(`Server is listening on port ${PORT}`)
})

This is the JSON I am trying to parse.这是我要解析的 JSON。 I validated this is valid JSON on those JSON validation sites.我在那些 JSON 验证站点上验证了这是有效的 JSON。

[
    {
        "gameID": "146",
        "steamAppID": "35140",
        "cheapest": "14.95",
        "cheapestDealID": "LNCZ5EicmEMiwyfYVw%2FNdGPos9V7MzoPId2UuwaBqvA%3D",
        "external": "Batman: Arkham Asylum Game of the Year Edition",
        "internalName": "BATMANARKHAMASYLUMGAMEOFTHEYEAREDITION",
        "thumb": "https://cdn.cloudflare.steamstatic.com/steam/apps/35140/capsule_sm_120.jpg?t=1634156906"
    }
]

https response is a stream that returns chunks of data in the data event, so you need to concatenate data there (store buffer raw data into an array), and parse it in the .end event, when the response is finished, and then you can use res.json to send it to the consumer: https response是一个 stream 在data事件中返回数据块,所以你需要在那里连接数据(将缓冲区原始数据存储到一个数组中),并在.end事件中解析它,当响应完成时,然后你可以使用res.json发送给消费者:

try this:尝试这个:

const express = require('express'); // Web Framework
const https = require('https');
const router = express.Router();

const api = 'https://www.cheapshark.com/api/1.0/games?title=batman&steamAppID=35140&limit=60&exact=0';

router.get("/", function(req, res) {

    https.get(api, (response) => {
        console.log(response.statusCode);

        const resData = [];

        response.on('data', (chunk) => {
            resData.push(chunk);
        });

        response.on('end', function() {

            try {
                const data = JSON.parse(Buffer.concat(resData).toString());
                console.log(data);
                res.json(data);
            } catch (err) {
                console.log(err);
            }
        });
    })
});

module.exports = router;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM