【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource - In Angular 4请求的资源上不存在“Access-Control-Allow-Origin”标头 - 在 Angular 4 中
【发布时间】:2018-08-17 00:08:18
【问题描述】:

数据服务.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 url 时出错。

【问题讨论】:

    标签: angular


    【解决方案1】:

    上述 API https://www.cryptocompare.com/api/data/coinlist/ 不支持跨域访问。您无法从其他域访问它。

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

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

    【讨论】:

      【解决方案2】:

      在 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");
      

      【讨论】:

      • 请解释您的代码以及为什么是答案的解决方案。不要局限于复制代码作为答案。
      猜你喜欢
      • 2019-07-21
      • 2018-01-03
      • 2015-08-29
      • 2018-10-31
      • 2016-08-17
      • 2018-06-09
      • 2015-09-01
      • 2019-07-04
      相关资源
      最近更新 更多