Amareis / another-rest-client

Simple pure TypeScript REST API client that makes your code lesser and more beautiful than without it.
MIT License
174 stars 16 forks source link

SyntaxError: Unexpected token u in JSON at position 0 #15

Closed felixlinker closed 6 years ago

felixlinker commented 6 years ago

Hi there,

I tried using this library and following code yielded an error:


const RestClient = require('another-rest-client');
global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

let api = new RestClient('http://localhost:8082/engine-rest');
api.on('error', function(err) {
    console.log('err');
});
api.res('engine');
api.engine.get().then(function(result) {
    console.log(result);
}, function(reason) {
    console.log(reason);
});

When debugging the code in Visual Studio Code the promise resolved successfully with result being undefined. Also the error callback was not called. The error displayed on the console is the following:

SyntaxError: Unexpected token u in JSON at position 0
    at parse (native)
    at safe (c:\Users\felix\Desktop\js-test\node_modules\another-rest-client\rest-client.js:80:17)
    at _createClass.value.xhr.onreadystatechange (c:\Users\felix\Desktop\js-test\node_modules\another-rest-client\rest-client.js:157:67)
    at exports.XMLHttpRequest.dispatchEvent (c:\Users\felix\Desktop\js-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:591:25)
    at setState (c:\Users\felix\Desktop\js-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:610:14)
    at IncomingMessage.<anonymous> (c:\Users\felix\Desktop\js-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:447:13)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)

Trying the same query in postman works just fine. The result body is:

[{"name":"default"}]

With following headers: Cache-Control →no-cache Content-Type →application/json Date →Mon, 05 Mar 2018 18:09:49 GMT Transfer-Encoding →chunked

Especially as the promise resolves successfully I don't see me doing anything wrong. But if so I'd be happy to see my error pointed out to me.

Best regards Felix

Amareis commented 6 years ago

Humm, maybe XHR node polyfill doing some wrong? Can you try to run this code in a browser?

felixlinker commented 6 years ago

Trying this out in browser "correctly" yields Access-Control-Allow-Origin error calling the supplied callbacks so I guess it's not your fault but one of the XMLHttpRequest library!