基本上,我試圖在呼叫 API 時從其中一個物體更新屬性“subscribed_status”。當屬性在我的 java 服務器中成功或不成功地被修補/更新時,我將在前端控制臺中相應地收到一條訊息,由于使用Collections.singletonMap以下列形式表示:
{回應:'失敗'},
{回應:'成功'}
問題是當我從后端得到這個時,我如何在我的 Reactjs 中設定如下條件?
//The condition doesn't work because data is not string. I'm not even sure
if(res.data==='FAILURE'){
//execute some sorts of command
}
為了更好地了解我的后端回傳到我的前端的內容,提供以下內容以供查看:
@PatchMapping("/updateSubscribedStatus/{email}")
public Map<String, String> updateSubscribedStatus(@PathVariable String email) throws AlreadySubscribedException {
try{
Boolean updateStatus=userService.updateSubscribedStatus(email);
if(updateStatus){
return Collections.singletonMap("response", "SUCCESS");
}
return Collections.singletonMap("response", "FAILURE");
}catch(Exception alreadySubscribedException){
return Collections.singletonMap("response", "FAILURE");
}
}
在我的前端,我使用 axios 呼叫 API 并在我得到 {response: 'FAILURE'} 的條件下呼叫一個函式:
export const updateSubscribedStatus=(email:string,setSubscribedStatus:(subscribedStatus:boolean)=>void,toggleShowAlreadySubscribedError:()=>void)=>{
axios.patch(`http://localhost:8080/user/updateSubscribedStatus/${email}`)
.then((res)=>{
console.log(res.data);
setSubscribedStatus(true);
// The following if statement is where I get stuck
if(res.data.toString()==="FAILURE"){
toggleShowAlreadySubscribedError();
}
}).catch((error)=>{
console.log(error);
setSubscribedStatus(false);
})}
我會感謝你的幫助!提前一百萬謝謝!
uj5u.com熱心網友回復:
在對 axios 了解不多的情況下,在我看來這res.data將是完整的有效負載,因此我希望res.data.response包含您的“FAILURE”字串。
此外,我確實認為正確的 RESTFul 實作方式是在成功的情況下回傳“HTTP 200 OK”,在已經訂閱的情況下回傳“HTTP 40x”(比如 HTTP 409)。您可以通過將 aResponseEntity<?>作為 @PathMapping 方法的回傳型別并回傳正確的代碼來實作此目的。
public ResponseEntity<?> updateSubscribedStatus(...) {
try {
...
return new ResponseEntity<Success>(HttpStatus.OK);
} catch (..) {
return new ResponseEntity<Error>(HttpStatus.CONFLICT);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/528152.html
標籤:爪哇反应api
