【问题标题】:how can i have the status code response from my backend?我怎样才能从我的后端获得状态码响应?
【发布时间】: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


【解决方案1】:

为了从后端响应中获取您的 HttpStatus,您必须首先将 {observe: "response"} 放入请求参数中(而不是在正文中)。

然后在映射中使用pipemap,您可以获取您的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命名Convention

【讨论】:

  • 感谢您的回答,但如果我也必须在后端执行某些操作以获取响应代码,请告诉我,如果即使获取请求也可以使用此代码,我也在徘徊,再次感谢:-)
  • 代码看起来“不错”应该可以工作,虽然我不明白 res=this.CS.postcompetenze(this.comp) ,发布整个控制器代码。在您编写的@PostMapping 代码中,该服务不适用于 Get 请求。
  • 顺便说一句,后端无法知道哪个是HttpStatus,直到你设置一个HttpStatus。默认情况下,spring 会处理您的响应状态代码,如果您想发送自定义 HttpCode 只需使用 ResponseEntity,可以在此处找到示例baeldung.com/spring-response-entity
  • 在您编写的代码 @PostMapping 中,该服务无法与 Get 请求一起使用。您必须使用 @GetMapping 或者如果您想为 2 Http 方法(例如获取和发布)使用相同的端点,您必须使用 @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
  • 但我的请求是发布请求,而不是获取请求,我正在编辑问题以更好地解释我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 2018-03-21
  • 2021-02-26
  • 2011-06-04
  • 2023-01-18
  • 1970-01-01
相关资源
最近更新 更多