JavaScript HTTP请求失败 [英] JavaScript HTTP request failed

查看:498
本文介绍了JavaScript HTTP请求失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以看看下面的代码来帮助我弄清楚我在做什么错吗?我收到此错误

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

错误XMLHttpRequest {readyState:1,超时:0,带有凭据: false,上传:XMLHttpRequestUpload,responseURL:" ...}

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

当我试图向NASA图像库请求获取图像时.

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)
})

推荐答案

您的else语句放置在错误的位置

Your else statement is in the wrong place

ajax请求通过这些不同的状态

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

readyState事件将随着这些状态的改变而触发,这就是为什么我们检查第四个状态是否是在请求完成后触发回调的状态,并获得返回的数据.

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.

您正在使用else语句,该语句实际上会在1或除4之外的任何状态上触发,但是1是第一个readyState,当首次设置请求时,您必须等待直到到达第四个readyState

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

这篇关于JavaScript HTTP请求失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆