gpt4 book ai didi

javascript - 回调中的 Socket.io-emit 给出 SyntaxError : Unexpected end of JSON input

转载 作者:行者123 更新时间:2023-12-03 04:49:29 25 4
gpt4 key购买 nike

所以我在这样的模块中导出回调函数:

(function() {

let request = require("request");

module.exports = function GithubApi(url, callback) {

let options = {
uri: url,
headers: {
"User-Agent": "Me",
"Content-Type": "application/x-www-form-urlencoded"
}
};

request(options, function(err, body) {

let context = {
issues: JSON.parse(body.body).map(function(issue) {
return {
title: issue.title,
comments: issue.comments,
};
})
};

callback(context) // The callback
});
};
}());

当我在带有express.js的GET请求中使用它时,这个回调工作得非常好:

app.get("/", (req, res) => {
let url = "some url";

GithubApi(url, (data) => {

res.render("../some-views", data);
});
});

但是当我添加套接字发出时,回调函数返回 SyntaxError: Unexpected end of JSON input

app.get("/", (req, res) => {
let url = "some url";

GithubApi(url, (data) => {

io.socket.emit("update", {message: data}); // adding this
res.render("../some-views", data);
});
});

无法理解为什么套接字会干扰请求并返回 JSON 错误。有人可以帮忙吗?

最佳答案

该问题一定是由于 body.body 不包含有效的 JSON 字符串引起的。

当你运行这样的代码时:

JSON.parse(body.body)

您应该始终使用 try/catch,因为 JSON.parse 会在错误的 JSON 上引发异常。

有关更多详细信息,请参阅这些答案:

关于javascript - 回调中的 Socket.io-emit 给出 SyntaxError : Unexpected end of JSON input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42720415/

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