Hoa
Hoa

Reputation: 20448

Why is Node.js not parsing the following page correctly?

If I access the following page (I know the credentials are invalid):

https://apis.live.net/v5.0/me/contacts?access_token=dummy_token

In the browser I get nicely formatted JSON:

{
   "error": {
      "code": "request_token_invalid", 
      "message": "The access token isn't valid."
   }
}

However, if I try to do the equivalent is Node.js

    var request = require('https').request({

        host: 'apis.live.net',
        port: 443,
        path: '/v5.0/me/contacts?access_token=' + 'dummy',
        method: 'GET'
    },

    function (httpsres) {
        var contacts = '';
        httpsres.on('data', function (result) {
            contacts += result;
        });

        httpsres.on('end', function () {
            console.log(contacts);
        });

    });

    request.end();

The output is mangled as follows:

}  }  "message": "The access token isn't valid."

How can I modify the program so that the output matches the result from the browser?

Upvotes: 0

Views: 60

Answers (1)

Amadan
Amadan

Reputation: 198476

The output is using \r (Carriage Return) for a line separator. Unix standard is \n (Line Feed), while Windows is \r\n (CR/LF). When you print out \r by itself, it will return the cursor to the start of the line, but not advance to the next line, and any further text will be overwriting what you just printed.

Specifically:

{\r
   "error": {\r
      "code": "request_token_invalid", \r
      "message": "The access token isn't valid."\r
   }\r
}

The first four lines just completely overwrite each other. After the "message" line is printed, the first five characters are overwritten by }; then the first character is overwritten by {.

Your response is fine; the printing of it is screwed up. To see the output as it really is, try piping your code into less, which will display \r as ^M, or into hexdump -C, which will show you 0d (instead of the usual 0a for \n).

Insert this just before you print:

contacts = contacts.replace(/\r/g, "\n");

and it will be fixed.

Upvotes: 2

Related Questions