我如何从我的后端得到状态码响应?



我有一个调用servlet的组件,该servlet向后端发送post HTTP请求(我使用spring boot),我希望后端返回我之前发送的post的状态;这就是我的代码:这里我调用servlet,如你所见,我希望在一个名为res

的变量中显示状态错误
res= this.CS.postcompetenze(this.comp)

就是servlet:

postcompetenze(raw: any):boolean{
var comp = '{'  +'"id"'+':'+'0'+','+'"nome"'+':'+'"'+raw[0]+'"'+','+'"descrizione"'+':'+'"'+raw[1]+'" }'
const obj = JSON.parse(comp);
var res=this.http.post<any>('http://localhost:8080/postcompetenza', obj).subscribe(
(val) => {console.log("POST call successful value returned in body", val);
})
if(res!= null)
return true
else
return false
}

,这是我在后台的端点:cs.addCompetenza(comp)是一个从jpa调用另一个函数的函数,该方法返回对象competenza。

@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postcompetenza") // aggiunge una competenza
public competenza addCompetenza(@RequestBody competenza comp) {
return cs.addCompetenza(comp);
}

所以我想再次使用状态码响应(200,300,400,…)来代替返回的对象。编辑:

@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postcompetenza") // aggiunge una competenza
public ResponseEntity<?> addCompetenza(@RequestBody competenza comp) {
try {
competenza response = cs.addCompetenza(comp);
return ResponseEntity.status(HttpStatus.OK).body(200);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(409);
} catch (BadRequest e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(400);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(500);
}
}

这是我的后端,我的前端:

postcompetenze(raw: any){
var comp = '{'  +'"id"'+':'+'0'+','+'"nome"'+':'+'"'+raw[0]+'"'+','+'"descrizione"'+':'+'"'+raw[1]+'" }'
const obj = JSON.parse(comp);
var res=this.http.post<any>('http://localhost:8080/postcompetenza', obj).subscribe(
(val) => {console.log("andata "+ JSON.stringify(val))
if(val == "200")
this.toastr.success("dipendente inserito correttamente","SUCCESSO");
else
this.toastr.error("dipendente non inserito","ERRORE")
},
(error) => {                              //Error callback
console.error('error caught in component '+error)
this.toastr.error("dipendente non inserito","ERRORE")
}
)

我正在做这一切,因为我需要显示一个成功或错误的toast,有了这个代码,我只能有成功toast,我不明白为什么我不能得到错误toast;谢谢你的帮助

为了从BackEnd响应中获得HttpStatus,您必须将第一个{observe: "response"}放入请求参数中(而不是在body中)。

然后使用带有映射的管道到映射中,您可以获取Http状态并将您想要的任何对象返回给订阅对象。(我希望这对你有意义)

this.http.get("https://jsonplaceholder.typicode.com/posts/1", {observe: "response"}).pipe(map(value => {
//Here you can check your the status or whatever request info you want to get(headers, response code,response body, type and ecc...) 
console.log(value.status);
return value.body; //returning just the body or whatever you wanna see into your subscribe object.
})).subscribe(data => {
//Here you have your body.
console.log(data);
});

+:

看一下Java命名约定

最新更新