angular - 如何在不更改后端的情况下解决 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
在错误消息中。我知道那里有很多类似的问题,但其中大多数配置了后端,我无权访问它。其余的对我不起作用。因此,任何帮助将不胜感激。
解决方案
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
推荐阅读
- unity3d - Shader Forge - 奇怪的节点问题
- vue.js - Vue Draggable 支持将项目保留在 From 数组中?
- c# - 转换和查找值
- webpack - 如何在 webpack 中为 scss url 添加前缀?
- python - 将句子列表加入短语
- php - jQuery 3 + Ajax + PHP 发送邮件表单不发送邮件
- python - BeautifulSoup 在特定标签中查找文本
- git - 在 Jenkinsfile 中隔离存储库分支的名称
- salesforce - 将参数从页面传递到控制器,而无需在 visualforce 中使用 apex:param
- go - 在 golang 中获取目录的校验和