-1

This is the open api and I am trying to fetch data using the URL. But I am getting this error. I can't set the backend to allow localhost. What is my option to make it work ?

Error

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

what I have tried

let header = new HttpHeaders();
header.set("Access-Control-Allow-Origin", "*");
const URL =
    "url here ";
return this.http.get(URL, { headers: header })
.pipe(map(res => res));

dumb11
  • 129
  • 1
  • 9

1 Answers1

0

Basically you want to access a server that is configured to deny requests from different origin clients.

You have two options IMO.

  1. Ask the API developer to allow you to request. In this, the API would be changed to allow requests from your app. The server-side implementation differs from platform to platform. For e.g. .Net Core refer this article.
  2. If the above option does not exist for you (The API developer refuses to do so) then use JSONP to bypass the CORS.

For e.g. below is a sample code from Kunal Tandon's blog.

<head>

<script>
    var myFunc = function(data) {
        console.log(data);
    }
</script>
<script src="xyz.com?wrap=myFunc"></script>

Refer Understanding JSON, JSONP, CORS, and bypassing CORS with JSONP for more information.

I would strongly suggest you change API because that is the correct way. The JSONP is just a workaround.

Kishan Vaishnav
  • 2,273
  • 1
  • 17
  • 45
  • Why down point? Can I get an explanation, please? I typed for like 20 mins to answer this question. – Kishan Vaishnav May 29 '20 at 13:52
  • I up voted for you. Thanks for the answer but that is not what I am after. I am using Angular 8 and there might be a header I can send with the request to the server. – dumb11 Jun 01 '20 at 20:13
  • I don't understand what you mean by "Header". I would like to know if there is some other solution to it. Can you point me in the direction? – Kishan Vaishnav Jun 02 '20 at 04:34