joseph michael
joseph michael

Reputation: 31

Confused why I got this error in Node.js (require.js)

I got this error in my script that was running perfectly smooth up until a random moment:

 undefined:3
    <!DOCTYPE html>
    ^

    SyntaxError: Unexpected token <
        at Object.parse (native)
        at Request._callback (C:\Users\Tom\Pictures\Bot\background.js:44:26)
        at Request.self.callback (C:\Users\Tom\Pictures\Bot\node_modules\request\request.js:199:22)
        at emitTwo (events.js:87:13)
        at Request.emit (events.js:172:7)
        at Request.<anonymous> (C:\Users\Tom\Pictures\Bot\node_modules\request\request.js:1036:10)
        at emitOne (events.js:82:20)
        at Request.emit (events.js:169:7)
        at IncomingMessage.<anonymous> (C:\Users\Tom\Pictures\Bot\node_modules\request\request.js:963:12)
        at emitNone (events.js:72:20)
        at IncomingMessage.emit (events.js:166:7)

By "random" I mean that it is happening at unpredicted times - I am running a bot that sends an AJAX request every 10,000 milliseconds (10 seconds). After a bit ( having tried it about 10 times ) it comes up with this error message and stops running. Line 3 of my code, which is where the error apparently is, involves the code:

var request = require("request");

I am not sure what the error is, but is it the way I handle my code?

var scan = function() {
    var interval = setInterval(function() {
        request({
            url: "http://www.roblox.com/catalog/json?CatalogContext=1&CurrencyType=0&CreatorID=1&pxMin=0&pxMax=0&SortType=0&SortAggregation=3&SortCurrency=0&IncludeNotForSale=true&LegendExpanded=true&Category=0&PageNumber=1",
            method: 'GET'
        }, function(err, res, body) {
            var r = body;
            if (r && r.length > 0) {
                r = r.toString();
                r = JSON.parse(r);
                var len = r.length;
                for (var i = 0; i < len; i++) {
                   //do stuff here
                }
            }
})
        }, 20);
}

Upvotes: 1

Views: 97

Answers (1)

Seth McClaine
Seth McClaine

Reputation: 10030

I'm assuming every once and a while Roblox.com is failing to respond to your call. You should be able to check (assuming they are sending status in the header back to you) if they think they are giving you a valid JSON response by checking to see if res == 200

     function(err, res, body) {
        if(res !== 200) { //if not success
            //handle issue here
            console.log(body);
            return;
        }
        var r = body;
        if (r && r.length > 0) {
            r = r.toString();
            r = JSON.parse(r);
            var len = r.length;
            for (var i = 0; i < len; i++) {
               //do stuff here
            }
        }
      } 

If that doesn't help, you can use a try catch block around your parse, at least it wouldn't cause your script to stop running when it does fail

Upvotes: 2

Related Questions