我正在尝试向后端发送GET请求(https://api.zenefits.com/core/people)我的Angular应用程序运行在localhost:4200上。我尝试了很多选项,阅读了很多博客文章,但找不到任何适合我的东西。我尝试使用代理方法来解决这个问题,因为我没有访问后端的权限,但这仍然会给我以下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'})});
}
}
以下是我的代理conf.json:
{
"/core/*": {
"target": "https://api.zenefits.com/core/people",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
我尝试了很多方法,但都徒劳无功。这些文档不清楚这些文件应该是什么样子。我不明白为什么错误消息中的URL也变为external/people
而不是core/people
。我知道有很多类似的问题,但大多数都配置了后端,我无法访问它。其余的问题对我不起作用。所以,如果有任何帮助,我将不胜感激。
您必须更改您的api url才能使用代理(使用相对url(,而不是直接使用api服务。
将以下变量更改为
this.employeeQueryUrl = '/core/people';
您的代理配置需要更新为
{
"/core/*": {
"target": "https://api.zenefits.com/",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
然后,代理将接收您的api调用,并将所有请求从/core/*
重定向到https://api.zenefits.com/core/*
这是Angular 的文档
您无法通过angular(前端(本身消除CORS错误,您还需要从后端解决它。
但对于有角度的部分,您可以使用proxy.config文件:
{
"/api/*": {
"target": "http://localhost:57263",
"secure": false,
"logLevel": "debug"
}
}
并向angular.json文件添加代理引用。
按照这些步骤,你就可以开始了(下面的链接解决了angular+node的问题,对于你的后端技术,只需谷歌搜索即可。(https://www.techiediaries.com/fix-cors-with-angular-cli-proxy-configuration/
希望它能有所帮助!!