【问题标题】:Why do I receive this error in an angular request? (CORS)为什么我在角度请求中收到此错误? (CORS)
【发布时间】:2018-04-25 10:43:04
【问题描述】:

我有这个控制器

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  url: string;

  constructor(private http: HttpClient){
    this.url = 'https://stats.nba.com/stats/leaguedashplayerbiostats?PerMode=Totals&LeagueID=00&Season=2017-18&SeasonType=Regular Season';

    this.http.get(this.url,)
      .subscribe(/*data => {*/
        data => {
          console.log("HOLA");
        },
        err => {
          console.log("Error occured.")
    });
  }
}

这是对 NBA API Stats 的请求,如果我在 Postman 中执行,我会看到所有数据,但如果我使用 Angular 4 执行,我会在 Chrome 开发者工具中看到下一个错误

加载失败 https://stats.nba.com/stats/leaguedashplayerbiostats?PerMode=Totals&LeagueID=00&Season=2017-18&SeasonType=Regular%20Season: 请求中不存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 访问。

我正在使用命令ng serve 运行服务器

我尝试了很多我在网上阅读的解决方案,但我认为唯一的解决方案是在后端进行更改

【问题讨论】:

  • 是的,你之前已经问过这个问题,而且你已经得到了回应。
  • 几乎就像错误所说的服务器没有设置“Access-Control-Allow-Origin”。
  • 如果您想知道为什么它不像邮递员那样失败,请参阅此问题:github.com/bttmly/nba/issues/34

标签: angular api request cors


【解决方案1】:

是的,您需要从您的站点配置服务器以使用 CORS。

为什么 Postman 可以正常工作?因为它不是浏览器。您完全控制邮递员的整个请求。

但是当你使用浏览器时,它会使用一些特定的方法来避免像 CSRF 这样的攻击。

【讨论】:

    猜你喜欢
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2022-01-09
    • 2022-07-09
    • 2020-03-10
    相关资源
    最近更新 更多