reactjs - 从 REST 响应中获取纯文本
问题描述
我使用 fetch 从我的 REST 服务中获取数据。响应到达后,我想获取错误消息(如果有),并将其显示给用户(用户主要是我)。
fetch(address, attributes).then(response => {
if (!response.ok) {
if (response.status === 404) {
return {
text: "Server not found!",
status: "danger"
};
}
return {
text: response.text(),
status: "danger"
};
}
return {
text: "Success!",
status: "success"
};
}
这response.text()
部分很重要:我的后端发送一个带有字符串作为实体的 javax.rs 响应,例如“错误”。在这里,我想阅读它,但是 response.text() 仅返回一个 Promise 对象,该对象在解决时仅返回更多 Promise 对象。
我也尝试使用{"msg":"[error]"}
然后在这里解析它reponse.json().msg
,但这也不起作用。
解决方案
// Success test case
fetch("https://jsonplaceholder.typicode.com/posts/1").then(response => {
if (!response.ok) {
if (response.status === 404) {
return {
text: "Server not found!",
status: "danger"
};
}
return response.text().then(text => {
return {
text: text,
status: "danger"
};
})
}
return {
text: "Success!",
status: "success"
};
}).then(resp => {
console.log("result:", resp);
})
// Failure test case 404
fetch("https://jsonplaceholder.typicode.com/posts/Not_Exist").then(response => {
if (!response.ok) {
if (response.status === 404) {
return {
text: "Server not found!",
status: "danger"
};
}
return response.text().then(text => {
return {
text: text,
status: "danger"
};
})
}
return {
text: "Success!",
status: "success"
};
}).then(resp => {
console.log("result:", resp);
})
// For testing Errors other then 404, i changed 404 error in the code because i couldn't get other HTTP Errors from placeholder api
fetch("https://jsonplaceholder.typicode.com/posts/Not_Exist").then(response => {
if (!response.ok) {
if (response.status === 999) {
return {
text: "Server not found!",
status: "danger"
};
}
return response.text().then(text => {
return {
text: text,
status: "danger"
};
})
}
return {
text: "Success!",
status: "success"
};
}).then(resp => {
console.log("result:", resp);
})
Yestext()
函数返回promise 对象。因此,一种解决方案可能是以这种方式使用它:
fetch(address, attributes).then(response => {
if (!response.ok) {
if (response.status === 404) {
return {
text: "Server not found!",
status: "danger"
};
}
return response.text().then(text => {
return {
text: text,
status: "danger"
};
})
}
return {
text: "Success!",
status: "success"
};
})
该json()
函数可以以相同的方式使用:
response.json().then(json => {
return {
text: json.msg,
status: "..."
};
})
快乐编码!
推荐阅读
- android - 如何在我的适配器类中编辑我的 recyclerview 图像?
- swift - 如何将自定义 UICollectionViewLayoutAttributes 向下转换为 apply() 方法?
- python - 将常量的用法与它们在 Sphinx 中的定义联系起来
- android - 等待firebase数据获取后从方法返回数据
- html - 容器外的图像只有一侧
- c++ - 如何通过引用或指针访问 2D 矢量
- php - Laravel 邮递员请求返回未经身份验证
- java - 从 Weblogic 获得的连接设置为自动提交
- maven - CI 和自动化
- angularjs - $http.post:大文件不起作用