Neha Shah
Neha Shah

Reputation: 1247

Getting cors error only when calling image url via http request but all apis are working so well other than this

Getting cors error only when calling image url via http request but all apis are working so well other than this.

Access to XMLHttpRequest at 'https://*********/diamond-grey.png' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

httpcall.ts

`let header = new Headers();
    header.set('Access-Control-Allow-Origin', '*');

    let options = new RequestOptions({ headers: header});
  await this.http.get(url,  {
        responseType: ResponseContentType.Blob,
      })
      .toPromise()
      .then((res: any) => {
        let blob = new Blob([res._body], {
          type: res.headers.get("Content-Type")
        });

        let urlCreator = window.URL;
        return this.domSanitizer.bypassSecurityTrustUrl(
              urlCreator.createObjectURL(blob));
        });`

Upvotes: 1

Views: 1833

Answers (2)

Rahul Tokase
Rahul Tokase

Reputation: 1218

CORS header needs to set on server side and not on the front end code.

In your angular code, Instead of loading the image using xml http request you can create the image tag and provide the src dynamically. Please note that Image tag allows the CORS request so you wont face this CORS issue.

Upvotes: 0

Doflamingo19
Doflamingo19

Reputation: 1639

to resolve CORS problem you need to filter the request servers side and after modify the header with your policy. Angular is used for front end, you cannot modify the header to resolve CORS in angular, you must do in server.

Upvotes: 1

Related Questions