javascript - 为什么 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)
})
解决方案
检查状态是否为 200 是不够的;你也需要检查this.readyState
。
标头(带有状态)将在 处可用this.readyState == 2
,但整个响应要到this.readyState == 4
.
推荐阅读
- java - 如何转换“收藏”
- web-applications - 将多个项目部署到单个应用服务中
- xpath - 使用 Google 表格进行 XPath 查询
- c# - 当宽度超过可用空间时,WPF 将中间控件移动到下一行
- android - Firebase 身份验证在登录时显示网络或超时错误
- forms - 为什么表单 input[type="checkbox"] 被 Firefox 视为只读但不应该?
- node.js - 测量在 docker 中运行的 NodeJS 应用程序的通用可扩展性定律的参数
- html - CSS位置相对:不考虑宽度
- google-cloud-platform - Increasing Google cloud snapshot frequency
- java - 无法通过 docker 容器读取文件