如何在Angular上处理CORS政策问题?

问题描述 投票:-3回答:2

该项目只是一个前端,没有使用服务器端语言,我想从区块链图表中获取实时数据,我已经看到了类似问题的答案,但是在其他框架上却见过。没有为angular指定任何值。我在src文件夹中创建了proxy.conf.json文件,并添加了以下代码,但是当我检查浏览器时仍然出现相同的错误


{
    "/api/*": {
        "target": "http://localhost:3000",
        "secure": false,
        "logLevel": "debug"
    }
}  

我已将proxy.conf.jason文件添加到angular.json下的serve部分,但仍然出现错误:

“从源'https://api.blockchain.info/charts/transactions-per-second?timespan=5weeks&rollingAverage=8hours&format=json'到'http://localhost:4200'处对XMLHttpRequest的访问已被CORS策略阻止:在所请求的资源上不存在'Access-Control-Allow-Origin'标头”

这是我的ApiService类别:


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

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private httpclient : HttpClient ) { }

    public dailychart(){
       return this.httpclient.get('https://api.blockchain.info/charts/transactions-per-second?timespan=5weeks&rollingAverage=8hours&format=json');
     }

}

javascript html angular http
2个回答
0
投票

Api.Blockchain的文档说

查询API纯文本查询api以检索来自blockchain.info的数据某些API调用可用于CORS标头,如果您将&cors = true参数添加到GET请求中

您可以在https://www.blockchain.com/api/q中查看其余文档

问候


0
投票

这不是您配置代理的方式。请看一下documentation,因为它看起来像您只是在没有实际配置的情况下放在示例代理中。还要注意,您仍然需要处理production的CORS问题,因为这仅在运行Angular开发服务器时有效。

但是,在开发过程中,您需要更改代理文件,以便定义一个虚拟端点,该虚拟端点将假装为实际资源的端点,然后在您的代码中使用该虚拟端点。

所以,为了您,将proxy.conf.json更改为

{
    "/blockchain-info": {
        "target": "https://api.blockchain.info",
        "secure": false,
        "logLevel": "debug"
    }
}  

ApiService至:

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

@Injectable({providedIn: 'root'})
export class ApiService {
  constructor(private httpclient: HttpClient) {}

  public dailychart() {
    return this.httpclient.get('/blockchain-info/charts/transactions-per-second?timespan=5weeks&rollingAverage=8hours&format=json');
  }
}

您可以看到我们不再尝试直接拨打https://api.blockchain.info的电话。相反,我们将它们设置为我们注册为/blockchain-info的代理。现在,当Angular看到您正在向/blockchain-info发出请求时,它将向您发出正确的URL的非CORS触发请求(在浏览器外部)。

© www.soinside.com 2019 - 2024. All rights reserved.