【问题标题】:Gettings No 'Access-Control-Allow-Origin' header is present error to external API获取外部 API 没有“Access-Control-Allow-Origin”标头存在错误
【发布时间】:2020-01-13 11:55:25
【问题描述】:

我不明白为什么,但是当我向外部 API 发送请求时,无论我做什么,都会不断收到 CORS 错误。我该如何解决这个问题?

import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class YtsService {
  url = 'https://yts.tl/api/v2/list_movies.jsonp';
  headers;

  constructor(
    private http: HttpClient,
  ) {
    this.headers = {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    };
  }

  getMovies(): Observable<any> {
    return this.http.get(this.url, { headers: this.headers });
  }
}

API 甚至不需要身份验证。

这是我在控制台中遇到的错误:

在“https://yts.tl/api/v2/list_movies.jsonp”访问 XMLHttpRequest 来自原点“http://localhost:4200”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

跨域读取阻塞 (CORB) 阻止了跨域响应 https://yts.tl/api/v2/list_movies.jsonp,MIME 类型为 text/html。看 https://www.chromestatus.com/feature/5629709824032768 了解更多 详情。

【问题讨论】:

    标签: angular cors


    【解决方案1】:

    您似乎正在尝试调用jsonp 端点,请尝试改用HttpClientJsonpModule 模块。可能不是cors 问题。

    示例见此链接:

    Angular jsonp calls

    【讨论】:

    • 我想可能是这样。今晚我会测试它谢谢!
    【解决方案2】:

    CORS 错误来自后端,而不是前端。您请求的 API 不允许来自您的源的请求 - 它很可能不是公共 API。您无法在前端执行任何操作来防止 CORS 错误,因为 CORS 是由后端实施的安全系统,用于防止不需要的请求。

    【讨论】:

    猜你喜欢
    • 2018-09-19
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2017-11-30
    • 2017-07-13
    • 1970-01-01
    相关资源
    最近更新 更多