【问题标题】:Angular No 'Access-Control-Allow-Origin'Angular 没有“访问控制允许来源”
【发布时间】:2020-01-21 20:39:40
【问题描述】:

我正在构建一个用于列出 euromillions 结果的 ionic+angular 应用程序,并且我正在尝试通过外部 api 获取数据,我不想使用服务器,它只是用于列出 api 结果,但我得到cors块,我不知道如何解决这个问题,有人可以帮助我吗?谢谢

lotteries.service.ts

import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { Euromillions } from './lottery.model';


@Injectable({
    providedIn: 'root'
})
export class LotteriesService {
    private euromillions: Euromillions[] = [
        {
            id: 'r1',
            numbers: '6-14-22-37-45',
            stars: '3-7',
            draw_info: 'Sorteio Nº076, 22-10-2019'
        }
    ];
    constructor(private httpService: HttpClient) { }

    getLastEuromillions() {
        return [...this.euromillions];
    }

    getApi() {

        return this.httpService.get('https://nunofcguerreiro.com/api-euromillions-json');
    }
}

lotteries.page.ts

import { Component, OnInit } from '@angular/core';

import { Euromillions } from './lottery.model';
import { LotteriesService } from './lotteries.service';

@Component({
  selector: 'app-lotteries',
  templateUrl: './lotteries.page.html',
  styleUrls: ['./lotteries.page.scss'],
})
export class LotteriesPage implements OnInit {
  euromillions: Euromillions[];

  constructor(private lotteriesService: LotteriesService) { }

  ngOnInit() {
    this.lotteriesService.getApi().subscribe((data)=>{
      console.log(data);
    }
    )};
}

image error

【问题讨论】:

    标签: javascript android angular cors


    【解决方案1】:

    AWS 的 API Gateway 将全天帮助您解决这个问题。

    当您运行 HTTP 请求时,最好从后端(使用 js/node)调用模块,这将帮助您解决 CORS 问题。但是,当您可以使用 AWS 时,为什么还要设置服务器/后端。

    通过一些额外的步骤,您可以创建一个传递请求的 API,然后从您的浏览器调用该 API,它将向您的页面发送允许跨域的响应。

    在这里查看我的其他答案: How to retrieve cross origin volcanic data in xml?

    【讨论】:

    • 哇,这很好用,很容易做到,非常感谢超级简单的解决方案:D
    • 酷,我知道。如果解决了问题,请确保将问题标记为答案,只需单击复选标记。最好的!
    【解决方案2】:

    外部浏览器阻止您的请求。 你有两个选择。 要么使用后端接收请求并重定向它。 或者 API 所有者允许跨域。 阅读此链接了解更多详情 mozila reference

    【讨论】:

      猜你喜欢
      • 2017-07-24
      • 2018-08-05
      • 2019-10-23
      • 2018-10-18
      • 2017-07-21
      • 2016-06-27
      • 2016-12-18
      • 2016-03-24
      相关资源
      最近更新 更多