无法解析节点 JS 中的 API 响应 - 响应似乎是一个数组

Cannot parse an API response in node JS - Response seems to be an array

我对此很陌生,我试图查看其他帖子,但找不到正确的答案。 我正在使用 Node JS https 调用 API 以获取有关 public 传输的状态信息。 响应似乎是 Object 的数组,但我似乎无法正确解析它。

这是我的代码:

//app set up
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const dotenv = require("dotenv").config();
const ejs = require("ejs");

const app = express();

app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));



 // get request to the page
app.get("/status", function(req,res){
    // get request to the API
 const url="https://api.tfl.gov.uk/Line/victoria/Status?app_id="+process.env.PRIMARY_KEY+"&app_key="+process.env.SECONDARY_KEY;
    
https.get(url, function(response){
        console.log (response);
        console.log(response.statusCode);
        console.log(response.headers);
        let responseBody = "";
        let parsedBody = [];
        response.setEncoding("utf-8");
        response.on("data", function(chunk){
            responseBody += chunk;
            console.log("this is the body response"+responseBody);
            console.log("this is the body response lenght"+responseBody.length);
            console.log("this is the body position 0 "+responseBody[0]);
            console.log("this is the body position 1 "+responseBody[1]);
        });     
        res.redirect("/");
});

headerreturns这个:

    {
  date: 'Sun, 08 Aug 2021 11:37:41 GMT',
  'content-type': 'application/json; charset=utf-8',
  'transfer-encoding': 'chunked',
  connection: 'close',
  'cache-control': 'public, must-revalidate, max-age=30, s-maxage=60',
  via: '1.1 varnish',
  age: '0',
  'access-control-allow-headers': 'Content-Type',
  'access-control-allow-methods': 'GET,POST,PUT,DELETE,OPTIONS',
  'access-control-allow-origin': '*',
  'api-entity-payload': 'Line,LineStatus',
  'x-backend': 'api',
  'x-cache': 'MISS',
  'x-cacheable': 'Yes. Cacheable',
  'x-frame-options': 'deny',
  'x-proxy-connection': 'unset',
  'x-ttl': '60.000',
  'x-ttl-rule': '0',
  'x-varnish': '935110596',
  'x-aspnet-version': '4.0.30319',
  'x-operation': 'Line_StatusByIdsByPathIdsQueryDetail',
  'x-api': 'Line',
  'cf-cache-status': 'DYNAMIC',
  'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
  server: 'cloudflare',
  'cf-ray': '67b874417d2b078e-LHR'
}

看来响应是一个 JSON 文件 -- 对吗?

responseBody 看起来像这样:

[{"$type":"Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities","id":"victoria","name":"Victoria","modeName":"tube","disruptions":[],"created":"2021-08-05T16:15:46.917Z","modified":"2021-08-05T16:15:46.917Z","lineStatuses":[{"$type":"Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities","id":0,"statusSeverity":10,"statusSeverityDescription":"Good Service","created":"0001-01-01T00:00:00","validityPeriods":[]}],"routeSections":[],"serviceTypes":[{"$type":"Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities","name":"Regular","uri":"/Line/Route?ids=Victoria&serviceTypes=Regular"},{"$type":"Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities","name":"Night","uri":"/Line/Route?ids=Victoria&serviceTypes=Night"}],"crowding":{"$type":"Tfl.Api.Presentation.Entities.Crowding, Tfl.Api.Presentation.Entities"}}]

如果我假设它是一个 object 的数组并记录它的长度和元素,我得到这个:

responseBody.length= 900
responseBody[0] = [
responseBody[1] = {

如果我使用 responseBody += JSON.parse(chunk) 我得到一个错误:

undefined:1
[{"$type":"Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities","id":"victoria","name":"Victoria","modeName":"tube","disruptions":[],"created":"2021-08-05T16:15:46.917Z","modified":"2021-08-05T16:15:46.917Z","lineStatuses":[{"$type":"Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities","id":0,"statusSeverity":10,"statusSeverityDescription":"Good Service","created":"0001-01-01T00:00:00","validityPeriods":[]}],"routeSections":[],"serviceTypes":[{"$type":"Tfl.Api.Presentation.Entities
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (C:\Users\THIS IS MY PATH\index.js:44:34)
    at IncomingMessage.emit (events.js:315:20)
    at IncomingMessage.Readable.read (internal/streams/readable.js:519:10)
    at flow (internal/streams/readable.js:992:34)
    at resume_ (internal/streams/readable.js:973:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

如果我使用 responseBody += JSON.parse(JSON.stringify(chunk)) 我又得到这个

 responseBody.length= 900
    responseBody[0] = [
    responseBody[1] = {

有什么建议吗?我是否收到了 JSON 以外的另一种格式的响应,所以我应该以不同的方式转换它?还是我的代码有问题? 谢谢

on("data") 回调中,您收到 数据,因此只有在所有块都已组装后才使用 JSON.parse 才有意义。所以你应该这样做:

response.on("data", (chunk) => {
  responseBody += chunk;           
});  

response.on("end", () => {
  const parsedJson = JSON.parse(responseBody);
  console.log(parsedJson);
}); 

附带说明 - 有许多库可用于 http 请求,它们可以开箱即用地执行此类操作,例如https://www.npmjs.com/package/node-fetch#json 举出一个。