gpt4 book ai didi

javascript - http get 请求的 Node json 错误

转载 作者:行者123 更新时间:2023-12-03 05:13:51 25 4
gpt4 key购买 nike

我们已经尝试解决这个问题有一段时间了。我知道堆栈溢出也有类似的问题,但没有一个解决方案对我有用,我需要一些帮助。我收到错误消息

undefined:1



SyntaxError: Unexpected end of JSON input
at Object.parse (native)
at IncomingMessage.<anonymous> (B:\-\memeFinder.js:27:20)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)

运行此代码时:

var http = require('http');

getRedditMemes();

function getRedditMemes () {
var options = {
host: 'www.reddit.com'
path: '/r/me_irl/hot/.json?count=20'
headers: {'User-agent':'xxxxx', 'Accept-Charset':'UTF-8'}
};

http.get(options, function (response) {
var str = '';

response.on('data', function (chunk) {
console.log(chunk)
str += chunk;
})

response.on('end', function () {
console.log(str);
var root = JSON.parse(str); //This line is where I'm getting the error
})
}).end();
}

我知道这里还有其他答案解释该错误是由于不完整的 json 造成的,但大多数适用的答案都说将解析代码放在我的response.on('end') 中已经在做了。这可能是一些愚蠢的小事情,但非常感谢您的帮助,谢谢。

编辑:谢谢大家的回复。我很感谢您的快速帮助。

最佳答案

请求返回 301(重定向)错误,并且 http 包未遵循该错误。您可以构建逻辑来遵循重定向,或者使用像 follow-redirects 这样的包装器:

将第一行更改为:

var http = require('follow-redirects').http;

关于javascript - http get 请求的 Node json 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41690139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com