Javascript GetHTTPSttaus代码获取API——反应本机
点击登录API将返回成功或失败响应。响应代码将被删除。在200到300之间成功。其余部分将被归类为故障响应。在我的场景中,如果它的成功响应是文本(response.text())。对于失败的情况,它将生成Json(response.Json()) 我想根据失败和成功对响应进行序列化 我一直沿用至今的方法Javascript GetHTTPSttaus代码获取API——反应本机,javascript,reactjs,react-native,ecmascript-6,fetch,Javascript,Reactjs,React Native,Ecmascript 6,Fetch,点击登录API将返回成功或失败响应。响应代码将被删除。在200到300之间成功。其余部分将被归类为故障响应。在我的场景中,如果它的成功响应是文本(response.text())。对于失败的情况,它将生成Json(response.Json()) 我想根据失败和成功对响应进行序列化 我一直沿用至今的方法 fetch(restUrl, { method: "POST", headers: { 'Accept': '*/*', 'Content-Type': 'applicatio
fetch(restUrl, {
method: "POST",
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
},
body: JSON.stringify(objReq)
}))
.then(response => {
if (response.status >= 200 && response.status < 300) {
response.text()
} else {
response.json()
}
)
.then(responseJson => {
let obj = responseJson;
if (responseJson != null && responseJson != undefined) {} else {
alert(i18n.t('unable'));
}
})
.catch(error => {
alert(error + "-from error");
});
fetch(restUrl{
方法:“张贴”,
标题:{
“接受”:“*/*”,
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify(objReq)
}))
。然后(响应=>{
如果(response.status>=200&&response.status<300){
答复.案文()
}否则{
response.json()
}
)
.然后(responseJson=>{
设obj=responseJson;
如果(responseJson!=null&&responseJson!=undefined){}else{
警报(i18n.t(‘无法’);
}
})
.catch(错误=>{
警报(错误+“-来自错误”);
});
它不接受这种方法。请提供合适的解决方案。我想您正在寻找类似的解决方案
const fetchRequest = (restUrl, objReq) => fetch(restUrl, {
method: "POST",
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
},
body: JSON.stringify(objReq)
})
.then(response => {
if (response.status >= 200 && response.status < 300) {
return response.text()
} else {
throw response.json();
}
})
.then(responseText => {
console.log('success',responseText);
})
.catch(errorJson => {
console.log(errorJson);
});
本质上,当你得到状态码而不是200,并且你忘记返回承诺时,只需抛出响应即可我想你正在寻找类似的东西
const fetchRequest = (restUrl, objReq) => fetch(restUrl, {
method: "POST",
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
},
body: JSON.stringify(objReq)
})
.then(response => {
if (response.status >= 200 && response.status < 300) {
return response.text()
} else {
throw response.json();
}
})
.then(responseText => {
console.log('success',responseText);
})
.catch(errorJson => {
console.log(errorJson);
});
本质上,当你得到状态码而不是200,并且忘记返回承诺时,只需抛出响应有一个有用的属性,它比=200&&<300
可读性强得多。有一个有用的属性,它比=200&&<300
可读性强得多