繁体   English   中英

Angular CORS请求失败

[英]Angular CORS request failed

我试图连接到Api( 不是我的 ),但出现CORS错误(屏幕1)。

然后我尝试在标题中添加“ Access-Control-Allow-Origin”:'*',但得到的结果相同(screen2)。

这是我的代码:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-analyzer',
  templateUrl: './analyzer.component.html',
  styleUrls: ['./analyzer.component.scss']
})
export class AnalyzerComponent implements OnInit {

  constructor(private http: HttpClient) {
    this.getDeck().subscribe(res => console.log(res));
  }

  ngOnInit() {
  }

  getDeck() {
    const headers = new HttpHeaders({
      'Access-Control-Allow-Origin': '*'
    });
    return this.http.get('https://www.keyforgegame.com/api/decks/30763530-041c-4e15-b506-3456e79141d2/',
      {headers: headers}
      );
  }

}

我不知道该怎么办..

谢谢

在此处输入图片说明 在此处输入图片说明

终于找到了一篇关于我的概率的优秀文章 它提到我有3个解决方案:

  1. CORS标头(需要服务器更改)==>然后,否

  2. JSONP ==> heeem ...否

  3. 代理服务器==>好吧..好的

我尝试第三个解决方案。 但说实话我很沮丧,所以我第一次尝试用一个很好的解决方案:我借用CORS代理(这一个相当不错)

然后我做下面的事情:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-analyzer',
  templateUrl: './analyzer.component.html',
  styleUrls: ['./analyzer.component.scss']
})
export class AnalyzerComponent implements OnInit {

  res;

  constructor(private http: HttpClient) {
    this.getDeck().subscribe(res => {console.log(res); this.res = res; });
  }

  ngOnInit() {
  }

  getDeck() {
    const headers = new HttpHeaders({
      'X-Requested-With': 'XMLHttpRequest'
    });
    return this.http.get('https://cors-anywhere.herokuapp.com/https://www.keyforgegame.com/api/decks/30763530-041c-4e15-b506-3456e79141d2/',
      {headers: headers}
      );
  }

}

最后,它的工作原理。

在此处输入图片说明

'Access-Control-Allow-Origin':'*'不应在您的请求中设置,而应在服务器的响应中设置。 希望您可以访问此服务器。

还可以考虑不使用通配符,而只允许使用http:// localhost:4200 无需向所有人开放。

邮递员的请求得到处理是因为它不关心CORS。 就像克里斯说的那样,应该在服务器(keyforge)中设置CORS。

我查看了该网站,看起来他们还没有任何api文档,因此,最好的办法是与他们的开发人员团队联系,并询问他们是否可以在其白名单中注册localhost:4000。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM