[英]Unexpected end of JSON input when JSON is valid
我正在使用 express 從公共 API 獲取數據並在我的前端使用數據。
這是我的字符路由,它在某些公共 API URL 上運行良好,但我嘗試的大多數都以意外的輸入錯誤結束而告終。
我還在Unexpected token, in JSON at position 48
。 當它看起來是有效的 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;
這是我使用字符路由的 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}`)
})
這是我要解析的 JSON。 我在那些 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
是一個 stream 在data
事件中返回數據塊,所以你需要在那里連接數據(將緩沖區原始數據存儲到一個數組中),並在.end
事件中解析它,當響應完成時,然后你可以使用res.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);
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.