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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With