javascript - E6 Ajax request not working -
i have script want fetch json data endpoint, error, script:
function httpget(url) { return new promise( function (resolve, reject) { var request = new xmlhttprequest(); request.onreadystatechange = function () { if (this.status === 200) { // success resolve(this.response); } else { // went wrong (404 etc.) reject(new error(this.statustext)); } } request.onerror = function () { reject(new error( 'xmlhttprequest error: '+this.statustext)); }; request.open('get', url); request.send(); }); } var url = 'https://api.jsonplaceholder.com'; httpget(url) .then(json.parse) .then((r) => { console.log(r); }).catch(function(error) { console.log(error); });
then, in console throws error:
error @ xmlhttprequest.request.onreadystatechange (app.js:11) @ app.js:18 @ promise () @ httpget (app.js:2) @ app.js:25
you can't check status
, have check readystate == 4
before can decide happened:
function httpget(url) { return new promise( function (resolve, reject) { var request = new xmlhttprequest(); request.onreadystatechange = function () { if (this.readystate === 4) { // *** if (this.status === 200) { // success resolve(this.response); } else { // went wrong (404 etc.) reject(new error(this.statustext)); } } // *** } request.onerror = function () { reject(new error( 'xmlhttprequest error: '+this.statustext)); }; request.open('get', url); request.send(); }); }
the spec says accessing this.response
before request complete should return empty string, me using chrome v57, doing gives error quoted. adding readystate
check fixes it.
Comments
Post a Comment