首页 > 解决方案 > 如何解决错误“请求的资源上不存在‘Access-Control-Allow-Origin’标头。” 在角度

问题描述

我正在向外部 api 发送请求并显示上述错误

这是我的T

import { Component, OnInit } from '@angular/core';
import {  HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
  selector: 'app-standings',
  templateUrl: './standings.component.html',
  styleUrls: ['./standings.component.css']
})

export class StandingsComponent implements OnInit {
 headers = new HttpHeaders();
  url1: any;
  constructor(private http: HttpClient) { 
  this.headers.append('X-RapidAPI-Key', 'myKey');
this.url1 = 'https://api.football-data.org/v2/competitions/SA/scorers';
  }
  getStandings() {
   return this.http.get(this.url1,{headers: this.headers})
        .subscribe(response => console.log(response))
}

  ngOnInit(): void {
    this.getStandings()
  }

}

我尝试将 'Access-Control-Allow-Origin': '*' 添加到 Httpheaders 构造函数,但我也遇到错误,

我也尝试创建一个代理配置文件并将其添加到 angular.json 但仍然存在错误

请帮忙 !

标签: angularhttp

解决方案


我相信您正在向不同的域发出请求,这就是浏览器由于同源安全性而不允许它的原因。这称为 CORS。

但是仍然有一些方法可以用来向不同的域发出请求。在浏览器中打开网络选项卡并Access-Control-Allow-Origin在响应正文中查找标头,它一定是缺失的。

阅读有关CORS的更多信息。


推荐阅读