cup_of
cup_of

Reputation: 6687

How to do a server side API call in Angular to bypass CORS error

I built an Angular 6 app that performs API requests on the client side. The simple API request lives in a service.ts file and looks like this:

  getApi(endpoint) {
    return this.http.get(`https://www.myapi.com/api-${endpoint}`);
  }

This getApi function gets called when a user clicks a button in the .html file.

Then comes this issue, I get the following error in the console when trying to do the http get request.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I was able to bypass this error and get the request successfully by installing this CORS plugin. The call worked, and my app worked so I know my code works. I want my app to work without this plugin.

After doing some research, I learned that this is an issue with the API I am using, not my apps issue. I even reached out to the API support and got this response:

I checked with the Devs and they confirmed that our API is not designed to be consumed from JS. JS -> SERVER WRAPPER -> AHREFS API (this is how the flow should be). So you should create a server-side wrapper to use AHREFS API.

So now my question, what exactly is a "server wrapper" in JS/Angular? Sounds like I need to call the API from the server side instead of the client side but I don't know how to do that yet.

I am seeking sample code, theory, or links for outside reading. I would prefer a solution that does not require re-writing my whole app, but I will if needed.

Upvotes: 1

Views: 1364

Answers (1)

Judd Franklin
Judd Franklin

Reputation: 570

The short answer is that a server wrapper would be a call by your front-end code to your own site's server. Then the server-side code would send out the API get request.

APIs have to manually enable browser-based requests, because the default treatment of such requests is to disallow them. This policy is in place because browser-based requests to a different domain can be very easily used to make malicious requests, generally known as Cross-site request forgery.

EDIT

After learning that your site is hosted on liquidweb, the following should enable you to do the server-side coding you need to do.

Liquidweb appears to be oriented towards WordPress hosting (this is extremely standard), so you should be able to run php.

So basically, all you need to do is put a php file in your public_html folder and code that PHP file to ping the API. The PHP file can be accessed at the url you would give to that file: //yoursite.com/file.php You can test this out locally if you are running a local server such as MAMP, WAMP, etc.

If you don't have those, you can run a simple PHP server via terminal if you have the PHP language installed on your computer.

Upvotes: 1

Related Questions