请求的资源上没有“Access-Control-Allow-Origin”标头 - 在Angular 4中

时间:2017-11-07 17:01:32

标签: angular

DataService.ts

import { Injectable } from '@angular/core'; 
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DataService {
  result:any;
  constructor(private _http: HttpClient) { }
  getPrices() {
    return 
     this._http.get('https://www.cryptocompare.com/api/data/coinlist/')
      .map(result => this.result = result);
  }
}

AppComponent.ts

import { Component } from '@angular/core';
import { DataService } from './data.service';

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

  objectKeys = Object.keys;
  cryptos: any;

  constructor(private _data: DataService) {}

  ngOnInit() {
    this._data.getPrices()
      .subscribe(res => {
        this.cryptos = res;
        console.log(res);
      });
  }

}

我收到了 - 请求的资源上没有“Access-Control-Allow-Origin”标头。我尝试访问此Rest API网址时出错。

2 个答案:

答案 0 :(得分:2)

提到的API https://www.cryptocompare.com/api/data/coinlist/不支持跨源访问。您无法从不同的域访问它。

阅读详情:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

作为替代方案,您可以让服务器从中获取数据。

答案 1 :(得分:0)

在API项目的StartUp.cs文件中

 ConfigureServices(IServiceCollection services) add below code
  services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("hereaddangularprojecturl"));
            });


and then Configure(IApplicationBuilder app, IHostingEnvironment env)
add below line of code

 app.UseCors("AllowSpecificOrigin");