JavaScript HTTP request failed

我的梦境 提交于 2019-12-24 04:06:29

问题


Could anybody take a look at below code help me to figure out what I am doing wrong ? I am getting this error

error XMLHttpRequest {readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: ""…}

when I am trying to make a request to NASA image galary to fetch a image..

HTML:

<img id="map" src="" alt="image from NASA"> 

JS:

var get = function(url){
    return new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status == 200){
                var result = xhr.responseText;
                result = JSON.parse(result);
                resolve(result);
            }else {
                reject(xhr);
            }
        }
        xhr.open("GET",url,true);
        xhr.send(null);
    })
}

get('https://api.nasa.gov/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo'
)
.then(function(response){
    console.log("success",response);
    document.getElementById('map').src = response.url;
})
.catch(function(err){
    console.log('error',err)
})

回答1:


Your else statement is in the wrong place

The ajax request goes thru these different states

State  Description
0      The request is not initialized
1      The request has been set up
2      The request has been sent
3      The request is in process
4      The request is complete

The readyState event will fire as these states change, which is why we check to see that the fourth state is the one triggering the callback, when the request is complete, and we have the returned data.

You are using an else statement that will fire on 1, or any state except 4 really, but 1 is the first readyState, when the request is first set up, you have to wait until it reaches the fourth readyState

var get = function(url){
    return new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4) {
                if (xhr.status == 200) {
                    var result = xhr.responseText;
                    result = JSON.parse(result);
                    resolve(result);
                }else {
                    reject(xhr);
                }
            }
        }
        xhr.open("GET",url,true);
        xhr.send(null);
    })
}

FIDDLE



来源:https://stackoverflow.com/questions/38881388/javascript-http-request-failed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!