首页 > 解决方案 > 如何从 node-express 获取图像并在 Angular 8 中查看图像

问题描述

我尝试从后端获取图像并在我的角度应用程序中查看并失败。

我的服务器路由:

app.get("/signature/:id", (req,res) => {
  res.send("./dest/signature.png");
})

客户服务:

  image() {
    return this.http.request('GET', this.baseUrl + '/signature/' + '1', {responseType: 'blob'}).toPromise();
  }

零件

 ngOnInit(){
 this.service.image().then((image) => {
      const imageURL = URL.createObjectURL(image);
      this.image = imageURL;
    });
}

我在浏览器上的错误:

core.js:6629 WARNING: sanitizing unsafe URL value blob:http://localhost:4200/406c69e3-93b6-4c00-8ec8-b43c7f266737 (see http://g.co/ng/security#xss)

unsafe:blob:http://localhost:4200/406c69e3-93b6-4c00-8ec8-b43c7f266737:1 GET unsafe:blob:http://localhost:4200/406c69e3-93b6-4c00-8ec8-b43c7f266737 net::ERR_UNKNOWN_URL_SCHEME

标签: node.jsangularexpress

解决方案


您可以创建一个管道来绕过此问题。

ng g pipe safeHtml

管道.ts:

@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {
  }

  transform(value: any, args?: any): any {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }

}

在您的模板中,只需编写

<img [src]="image | safeHtml"></div>

推荐阅读