代码之家  ›  专栏  ›  技术社区  ›  dEs12ZER

为什么我在试图把安古拉5的Put请求发送到Spring Boot时未经授权?

  •  0
  • dEs12ZER  · 技术社区  · 7 年前

    我试图将一个来自Angular5的Put请求发送到SpringAPI,但我得到了一个错误。

    这是角度干预.service.ts:

    updateIntervention(id:number){
            if(this.authService.getToken()==null) {
              this.authService.loadToken();
            }
            return this.http.put(this.host+"/updateIntervention/"+id,
           {headers:new 
           HttpHeaders({'Authorization':this.authService.getToken()})});
          }
    
      Intervention.component.ts 
    
        valider(ref: Intervention){
            this.intervService.updateIntervention(ref.id)
              .subscribe((data:any)=>{
                console.log('there is no error ! ');
              },err=>{
                console.log('there is an error ! ');
              })
    
            ref.valid = !ref.valid;
    
           }
    

    在弹簧靴中:

    @RequestMapping(value="/updateIntervention/{id}",method = RequestMethod.PUT)
        public Intervention update(@PathVariable Long id){
    
            System.out.println("in intevention update");
            Intervention I = new Intervention();
            I = interventionRepo.getOne(id);
            I.setValid(true); // it's boolean , this is the goal from this update
            interventionRepo.save(I);
    
            return I  
        }
    

    当我在角度上出错时:

    {"timestamp":1527443447949,"status":401,"error":"Unauthorized"}
    

    由于弹簧启动错误:

    access.AccessDeniedException: Access is denied
    

    PS:当我发送角度ID和对象引用时,这是有效的,在春天,我写

     public Intervention update(@PathVariable Long id , @RequestBody Intervention I){ ... }
    

    但我不需要这样做,因为我只想修改实体干预中有效的属性。

    我正在使用httpclient。

    知道吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Anis Tissaoui    7 年前

    您使用的Put方法具有以下定义:

    put(url: string, body: any | null, options)
    

    您将options对象作为body参数提供。这就是为什么您得到未经授权的401,它代表“未经授权”。表示您的凭证错误或丢失。

    你应该换一下

    return this.http.put(this.host+"/updateIntervention/"+id,
       {headers:new 
       HttpHeaders({'Authorization':this.authService.getToken()})});
      }
    

    到:

    return this.http.put(this.host+"/updateIntervention/"+id,
           null,
           {headers:new 
           HttpHeaders({'Authorization':this.authService.getToken()})});
          }