Search code examples
angularhere-api

How do I use Here Geocoding and search api from angular service with API key


I'm new to Angular, I want to use Here Geocoding api in my angular service, I appended my apiKey to the httpParams but it didn't work. Here is my code in the service:

    let params = new HttpParams();
    params = params.append('at', `${coordinates.latitude},${coordinates.longitude}`);
    params = params.append('q', query);
    params = params.append('limit', limit);
    params = params.append('apiKey', environment.apiMapRest);
    return this.httpClient.get('https://discover.search.hereapi.com/v1/discover', {params});

Here is the error:

Access to XMLHttpRequest '
from origin 'http://localhost:4200' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

I can access it directly in my browser and postman btw.


Solution

  • This is because from the browser a cross origin call was made. Here can be found the details about the cross origin policy. There hereapi also documents this case here.

    I would put the hereapi request logic on the backend of the Angular application. This way the Angular app would only communicate with his own backend, and would not do any cross origin calls. On the other hand if the hereapi calls are on backend side, the apikey is not exposed. (If the hereapi is called directly from Angular side, the apikey can be taken easily.)