首页 > 解决方案 > 为什么 if 语句不检查下面的 http 请求的状态?

问题描述

发送 http 请求后,我检查状态是否为 200 然后 resolve() 但如果语句似乎不起作用

 function getMelumat(){
        let promise = new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest();
        xhr.open("GET",'https://jsonplaceholder.typicode.com/posts');
        xhr.send()
        xhr.onload = ()=>{
            if ( this.status == 200){
                resolve(this.response)
            }
            else{
               throw "AN ERROR OCCURED"
           }
          }

        })

     return promise

    }


            getMelumat().then(data=>{
                return JSON.parse(data)
            }).then(data=>{
                console.log(data)
            })

标签: javascripthttpxmlhttprequest

解决方案


检查状态是否为 200 是不够的;你也需要检查this.readyState

标头(带有状态)将在 处可用this.readyState == 2,但整个响应要到this.readyState == 4.


推荐阅读