gpt4 book ai didi

javascript - GetHTTPSttaus 代码获取 API——React Native

转载 作者:行者123 更新时间:2023-12-01 02:34:06 24 4
gpt4 key购买 nike

点击登录 API 将返回成功或失败响应。响应代码将是。 200到300之间为成功。休息将被归类为失败 react 。在我的场景中,如果其成功响应,它将是文本(response.text())。对于失败情况,它将产生 Json(response.json())。

我想根据失败和成功序列化响应。

到目前为止我遵循的方法

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");

});

它不接受这种做法。请提供合适的解决方案。

最佳答案

我认为您正在寻找类似的东西

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

你可以这样调用它。

fetchRequest('url.com',{test:123});

本质上,当你得到 200 以外的状态代码并且你忘记返回 promise 时,只需抛出响应

关于javascript - GetHTTPSttaus 代码获取 API——React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48074778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com