首页 > 解决方案 > 无法在我的前端获得发布请求的状态

问题描述

我有一个弹簧启动控制器,我正在尝试返回我的前端(我使用 angular cli)http post 请求的响应值(200,300,400,...),问题是当 post 请求失败时我的代码不返回状态错误,我真的不明白为什么;我需要前端的请求状态,以便在成功或错误的情况下显示 toastr 这是我的前端代码:

postdipendenti(raw: any,comp:any,gr:any,fp:any){
    var dip = '{'  +'"id"'+':'+'0'+','+'"nome"'+':'+'"'+raw[0]+'"'+','+'"cognome"'+':'+'"'+raw[1]+'"'+','+'"data_nascita"'+':'+'"'+raw[2]+'"'+','+'"mail"'+':'+'"'+raw[3]+'"'+','+'"telefono"'+':'+raw[4]+','+'"setCompetenze"'+':'+JSON.stringify(comp)+',"listaGr":'+JSON.stringify(gr)+',"fp":'+JSON.stringify(fp) +'}'
    const obj = JSON.parse(dip);
    console.log("non json ->"+ dip)
    var res=this.http.post<any>('http://localhost:8080/postdipendente_competenze', obj).subscribe(
        (val) => {console.log("andata "+ JSON.stringify(val))
        if(val == "200")
            this.toastr.success("dipendente inserito correttamente","SUCCESSO");
        },
        (error) => {                              //Error callback
        console.log('error caught in component '+error)
        this.toastr.error("dipendente non inserito","ERRORE")
        }
    )
    
}

这是我的后端:

@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("postdipendente_competenze") // aggiunge un nuovo dipendente con competenze esistenti
public ResponseEntity<?> addDipendenteCompetenze(@RequestBody dipendenteRequest dipReq) {
    try {
        ds.addDipendenteCompetenze(dipReq);//function that does the post request
        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);
    }

}

我究竟做错了什么?我被卡住了,我不明白为什么。欢迎任何帮助,谢谢。

标签: javascriptangulartypescriptspring-bootangular-cli

解决方案


推荐阅读