【问题标题】:Binance API and angular 4 httpClientBinance API 和 Angular 4 httpClient
【发布时间】:2018-06-20 13:00:16
【问题描述】:

我有一个关于加密市场币安的问题。 他们有公共 api,尽管我可以在 Angular 中使用它来创建交易应用程序。

但是我有一些麻烦。 在 chrome 中使用该链接我得到 json 结果。 https://api.binance.com/api/v1/exchangeInfo

但使用 Angular 4 httpClient:

this.http.get('https://api.binance.com/api/v1/exchangeInfo').subscribe(res => console.log(res));

我有错误:跨域请求被阻止:同源策略不允许读取 api.binance.com/api/v1/exchangeInfo 上的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)

它不起作用。我不明白,为什么我不能在 Angular 应用程序中使用该 API?https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md

我该怎么办? 我应该这样设置标题:

getMarkets() {
    const headers = new HttpHeaders();
    headers.set('Content-Type', 'application/json');
    headers.set('Accept', 'application/json');
    headers.set('Access-Control-Allow-Headers', 'Content-Type');
    headers.set('Access-Control-Allow-Origin', '*');

    const path = 'https://api.binance.com/api/v1/exchangeInfo';
    return this.http.get(path, {headers: headers});
}

提前致谢

【问题讨论】:

  • 这里没有足够的细节来开始猜测。考虑使用与 HTTP 请求良好对应的异步技术(即 not RxJS)。
  • 为什么不用 RxJS?你能解释一下吗?
  • RxJS 在您有零个或多个结果的流时很有用。使用 HTTP 请求,您总是有 一个 结果。它很笨拙且容易出错,并且会丢弃可用的language level facilities

标签: javascript angular http typescript cors


【解决方案1】:

你不能这么直接使用它,币安 API 没有设置 CORS 头,所以 Chrome 和所有主流浏览器都会阻止请求。 还有一点,但本质上,需要启用 CORS 支持的 api 服务器应该将 Access-Control-Allow-Origin 设置为 * 或单个域 www.example.com,这允许浏览器阻止站点上的恶意代码从您可能登录的其他站点调用并读取某些数据的响应(例如:银行信息) 你可以阅读更多关于它here

一种可能的解决方案是拥有自己的服务器来代理对 binance 的调用

如果您要进行测试,另一种解决方案是使用 CORS 启用扩展,例如 this one

更新:如果满足您的数据需求,您也可以使用 websocket API docs

更新 2:这是一个很好的 stackoverflow question on cors

附注:如果您银行的 API 服务器将 Access-Control-Allow-Origin 设置为 *,则更改银行 :)

【讨论】:

    【解决方案2】:

    HttpHeaders 是不可变的。所以你必须写

    const headers = new HttpHeaders().
        set('Content-Type', 'application/json').
        set('Accept', 'application/json').
        set('Access-Control-Allow-Headers', 'Content-Type').
        set('Access-Control-Allow-Origin', '*');
    

    const headers = new HttpHeaders(
        {
          Content-Type:'application/json'),
          Accept:'application/json'),
          Access-Control-Allow-Headers:'Content-Type'),
          Access-Control-Allow-Origin:'*')
        })
    

    【讨论】:

    • 仍然在浏览器中我有错误:跨域请求被阻止:同源策略不允许读取api.binance.com/api/v1/exchangeInfo 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
    • @AdamAdamski 您收到 CORS 错误?你为什么不在你的问题中包含这些信息?! Eliseo set 在您的示例中如何表现得一成不变?这没有任何意义。
    • 是的,我有 cors 错误。我忘了提到它。你能帮我解决这个问题吗?
    【解决方案3】:

    试试这个不带标头的简单请求。

     this.http.get('https://api.binance.com/api/v1/exchangeInfo').subscribe(data => {
          this.results = data;
        });
      }
    

    对我有用

    【讨论】:

    • 它对我不起作用。可以试试 console.log(this.results) 吗?有用吗?
    猜你喜欢
    • 1970-01-01
    • 2018-01-10
    • 2018-05-09
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    相关资源
    最近更新 更多