Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to address CORS issue in Angular 8 without changing the backend?

Tags:

cors

angular

I am trying to send a GET request to the backend (https://api.zenefits.com/core/people) from my Angular app which runs on localhost:4200. I have tried many options and read many blog posts but couldn't find anything that works for me. I tried to use the proxy method of solving this problem since I don't have access to the backend but that is still giving me the following CORS error:

Access to XMLHttpRequest at 'https://api.zenefits.com/external/people/' (redirected from 'http://localhost:4200/core/people') from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The following is my service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  employeeQueryUrl: string;
  constructor(private http: HttpClient) {
    this.employeeQueryUrl = 'https://api.zenefits.com/core/people';
  }

  getAllEmployees() {
    return this.http.get(
      this.employeeQueryUrl, {
        headers: new HttpHeaders({
          Authorization: 'Bearer elZxQlHDSUallvL3OnnH'})});
  }
}

The following is my proxy.conf.json:

{
    "/core/*": {
      "target": "https://api.zenefits.com/core/people",
      "secure": false,
      "changeOrigin": true,
      "logLevel": "debug"
      }
}

I have tried many methods but in vain. The docs are not clear on how should the files look. I am not able to understand why the URL has changed to external/people instead of core/people in the error message too. I know there are a lot of similar questions out there but most of them configure the backend and I don't have access to it. The rest are not working for me. So, any help would be appreciated.

like image 657
theJediCode Avatar asked Sep 15 '25 14:09

theJediCode


1 Answers

You have to change your api url to use the proxy (using a relative url), not the api service directly.

Change the following variable to

this.employeeQueryUrl = '/core/people';

And your proxy config needs to be updated to

{
    "/core/*": {
      "target": "https://api.zenefits.com/",
      "secure": false,
      "changeOrigin": true,
      "logLevel": "debug"
      }
}

Then, your api call will be picked up by the proxy, and redirect all request from /core/* to https://api.zenefits.com/core/*

Here is the documentation from Angular

like image 190
John Avatar answered Sep 18 '25 09:09

John