繁体   English   中英

Angular 6 无法使用代理从外部服务器 API 获取数据

[英]Angular 6 Unable to get data from external server API using proxy

我正在使用本地 angular 应用程序,但在从外部服务器上的 API 获取数据时遇到问题。 我尝试使用代理,所以我创建了文件proxyconfig.json并通过以下方式将它包含在命令行中

ng serve --proxy-config proxyconfig.json

这是内容:

{
    "/api/*": {
    "target": "https://bittrex.com/api/v1.1/public/",
        "secure": false,
        "pathRewrite": {
            "^/api": ""
        },
        "changeOrigin": true
    }
}

我需要传递变量,所以我创建了服务OrderBookService

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { OrderBook } from './order-book.model';


@Injectable({
    providedIn: 'root',
  })
export class OrderBookService {
    constructor(private httpClient: HttpClient) {

    }
    getOrderBookBittrex(currency1: string, currency2: string): Observable<OrderBook[]> {
        const url = `http://localhost:4200/api/getorderbook?market=${currency1}-${currency2}&type=both`;
        return this.httpClient.get<OrderBook[]>(url);
    }
}

问题是当我想获取这些数据并将其保存到我的组件中的变量时,路径没有正确转换:它正在向http://localhost:4200/api/getorderbook?market=BTC-LTC&type=both发送请求而不是https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-LTC&type=both

  private getTransfers(): void {
    const currency1 = 'BTC';
    const currency2 = 'LTC';
    this.orderBookService.getOrderBookBittrex(currency1, currency2)
      .subscribe(orders => {
        this.orderBook = orders;
      });
  }

这是控制台日志

有谁知道如何正确地做到这一点?

当我像这样将所有路径放入 proxconfig.json 时,它工作正常:

{
    "/api/*": {
        "target": "https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-LTC&type=both",
        "secure": false,
        "pathRewrite": {
            "^/api": ""
        },
        "changeOrigin": true
    }
}

但我需要传递变量。

你编码

getOrderBookBittrex(currency1: string, currency2: string): Observable<OrderBook[]> {
    const url = `http://localhost:4200/api/getorderbook?market=${currency1}-${currency2}&type=both`;
    return this.httpClient.get<OrderBook[]>(url);
}

只需更改网址即可

getOrderBookBittrex(currency1: string, currency2: string): Observable<OrderBook[]> {
    const url = `/api/getorderbook?market=${currency1}-${currency2}&type=both`;
    return this.httpClient.get<OrderBook[]>(url);
}

您不需要在代码中使用http://localhost:4200

"pathRewrite": { "^/api": "" },不需要太多

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM