【发布时间】:2021-10-17 17:10:18
【问题描述】:
我有一个调用 servlet 的组件,该 servlet 向后端发送一个 post http 请求(我使用 spring boot),我希望后端返回我之前发送的 post 的状态; 那是我的代码: 在这里我调用 servlet,如您所见,我希望在名为 res 的 var 中显示状态错误
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调用另一个函数的函数,这个方法返回objecrt 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")
}
)
我这样做是因为我需要显示成功或错误的祝酒词,使用此代码我只能收到成功祝酒词,我不明白为什么我无法收到错误祝酒词; 感谢您的帮助
【问题讨论】:
-
我认为您可以尝试
mapping 响应代码,而不是订阅 val
标签: javascript typescript spring-boot jpa