首页 > 解决方案 > 如何在不更改后端的情况下解决 Angular 8 中的 CORS 问题?

问题描述

我正在尝试从在 localhost:4200 上运行的 Angular 应用程序向后端( https://api.zenefits.com/core/people )发送 GET 请求。我尝试了许多选项并阅读了许多博客文章,但找不到任何适合我的东西。我尝试使用代理方法解决此问题,因为我无权访问后端,但这仍然给我以下 CORS 错误:

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.

以下是我的服务:

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'})});
  }
}

以下是我的 proxy.conf.json:

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

我尝试了很多方法,但都是徒劳的。文档不清楚文件的外观。我无法理解为什么 URL 已更改为,external/people而不是core/people在错误消息中。我知道那里有很多类似的问题,但其中大多数配置了后端,我无权访问它。其余的对我不起作用。因此,任何帮助将不胜感激。

标签: angularapicors

解决方案


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


推荐阅读