saruftw
saruftw

Reputation: 1174

API request in Node returning error

I am making a simple http request to the Sphere Engine API with some request parameters . However, I cannot interpret the error . API specification : http://sphere-engine.com/services/docs/compilers#status

Code:

http = require('http') ;

var info = {
    sourceCode: 'print 3+4',
    language: 4,
    input: ''
} ;

var infoString = JSON.stringify(info);

var options = {
    host: 'api.compilers.sphere-engine.com',
    port: 80,
    path: '/api/v3/submissions?access_token=b11bf50b8a391d4e8560e97fd9d63460',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': infoString.length
    }
} ;

var req = http.request(options,function(res) {
    res.setEncoding('utf-8');
    var responseString = '' ;
    res.on('data', function(data) {
        responseString += data ;
    });
    res.on('end', function() {
        var resultObject = JSON.parse(responseString);
    });
} );

req.write(infoString);
req.end();

Error:

undefined:0

^
SyntaxError: Unexpected end of input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (/Users/sarthakmunshi/nodetry.js:29:27)
    at IncomingMessage.emit (events.js:117:20)
    at _stream_readable.js:943:16
    at process._tickCallback (node.js:419:13)

Upvotes: 1

Views: 132

Answers (1)

Magomogo
Magomogo

Reputation: 954

This error caused by JSON.parse(responseString);. You get response as not-json string (XML, HTML?), but try to parse it as a json.

You can use xml-stream library to parse XML.

Upvotes: 2

Related Questions