DevTool
DevTool

Reputation: 319

How to get image from node-express and view the image in Angular 8

I try to get an image from backend and view in my angular app and fail.

My server route:

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

ClientService:

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

Component

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

my Error on browser:

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

Upvotes: 2

Views: 2148

Answers (3)

ng-hobby
ng-hobby

Reputation: 2199

You don't need to create an image URL based on some Image object. Just you can get the full path URL of image from Back-end and simply display it in your Angular App using img tag.

 <img [src]="{{res.img_url}}" alt="image-txt">

Upvotes: 0

Gorav Singal
Gorav Singal

Reputation: 538

The correct API is: sendFile

http://expressjs.com/en/api.html

Alternate ways:

  1. You can return a stream of image.
  2. You can put your images at some place exposed to public. And can just return URL of that image.

Upvotes: 1

Tobias Kaufmann
Tobias Kaufmann

Reputation: 675

You can create a pipe to bypass this issue.

ng g pipe safeHtml

pipe.ts:

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

  constructor(private sanitizer: DomSanitizer) {
  }

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

}

In your template, simply write

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

Upvotes: 2

Related Questions