簡體   English   中英

Angular http 響應作為錯誤參數,即使狀態為 200

[英]Angular http response as error argument, even if the status is 200

所以我試圖從我的 spring 引導后端發出“GET”請求,我收到響應,但圖片作為錯誤參數出現。 我可以使用錯誤參數並使用網站上的圖片,但即使狀態為 200,我仍然會收到錯誤消息。

后端代碼:

@CrossOrigin(origins="http://localhost:4200")
@GetMapping(
  path = "/images/path-variable/{name}"
)
static public ResponseEntity<String> getImageWithMediaType(@PathVariable String name) throws IOException, Exception {
    System.out.println("/images/" + name + ".jpg");
    File tempFile = new File("/home/ninhow/Desktop/antons-skafferi-front-back/backend/src/main/resources/images/restaurant_1280x853.jpg");

    return ResponseEntity.ok(CodecBase64.encode(tempFile, true));
}

在 angular 我向我的服務提出請求:

@Injectable({
  providedIn: 'root'
 })
export class GetImageService {

constructor(private http: HttpClient) { }

getImage(){
  return this.http.get<any>("http://localhost:8080/images/path-variable/restaurant_1280x853");
  }
}

我用來接收響應並使用它的組件 function :

export class HeaderComponent implements OnInit {
image: any;

 constructor(private service: GetImageService, private sanitizer: DomSanitizer) { }
 ngOnInit() {
  this.getHeaderImage();
 }

 getHeaderImage(){
    this.service.getImage().subscribe(data => {
    console.log(data);
    this.image = "data:image/jpeg;base64" + data;
 }, error=>{
    var response = "data:image/jpeg;base64," + (error as any).error.text
    console.log(error);
    this.image = this.sanitizer.bypassSecurityTrustResourceUrl(response);
    });
 }

}

基本上我想做的是從我的后端發送一張圖片,這樣我就可以在我的前端使用而不會出錯:

組件的 html 文件:

<p>header works!</p>
<div>
   <img [src]="image" alt="">
</div>

瀏覽器控制台錯誤:

https://i.stack.imgur.com/gumCw.png

編輯我的 getImage function 后,function 看起來像這樣:

  getImage(){
return this.http.get("http://localhost:8080/images/path- 
  variable/restaurant_1280x853", {
  responseType: "text"
  });
}

在此處輸入圖像描述

因此,在上述評論的幫助下,我找到了解決問題的方法。 因此,解決方案的第一部分是將getImage() function 中的 get 重載更改為:

getImage(){
    return this.http.get("http://localhost:8080/images/path-variable/restaurant_1280x853", {
      responseType: "text"
   });
}

我不得不添加一個responseType:"text"作為選項,因為它需要一個 json 並且它正在接收一個 base64 字符串。

后來我遇到了一個問題: 在此處輸入圖像描述

我對此的解決方案是將'data:image/jpg;base64,'添加到消毒劑中,我還沒有弄清楚為什么這樣有效,但它解決了問題。 我最好的猜測是我告訴 header 它是一個 base64 字符串。

最終 function:

  getHeaderImage(){
    this.service.getImage().subscribe(data => {
      this.image = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,' + data);    
    }, error=>{
    console.log(error);
    });
  }

我的頁面在開始時加載了 null 結果,我不明白自從在ngOnInit()上調用 function 以來,我的解決方案是將*ngIf="image"添加到 ZFC35FDC70D5iamFC69D2698EZ8CA8 文件中,如果:加載了圖像,否則使用源...不要。

最終 html:

<div>
    <img *ngIf="image" [src]="image">

</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM