Jesper
Jesper

Reputation: 2094

Socket.io-emit in callback gives SyntaxError: Unexpected end of JSON input

So I'm exporting a callback-function in a module like this:

(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
        });
    };
}());

And this callback works perfectly fine when I'm using it in my GET-request with express.js:

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

    GithubApi(url, (data) => {

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

But when I add a socket-emit, the callback-function returns 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);
    });
});

Can't understand why the socket would interfere with the request and return an error with JSON. Can anybody help?

Upvotes: 0

Views: 831

Answers (2)

Jesper
Jesper

Reputation: 2094

So the problem was with the io.sockets.emit("update", {message: data});. For some reason, that interfered with the request(still don't know why tough). I guess it has something to do with the socket broadcasting to all channels, and that causes some kind of error, read something about it here.

So I changed the call to the callback-function to this:

GithubApi(orgs, repo, token, (data) => {

    io.of("/").emit("update", {message: data}); // This line made it work
    res.render("../views/home", data);
});

Upvotes: 0

rsp
rsp

Reputation: 111434

The probablem must be caused by the fact that body.body doesn't contain a valid JSON string.

When you run code like this:

JSON.parse(body.body)

you should always use try/catch because JSON.parse throws exceptions on bad JSON.

See those answers for more details:

Upvotes: 1

Related Questions