【发布时间】:2020-01-09 14:19:50
【问题描述】:
我正在使用本地 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
}
}
但我需要传递变量。
【问题讨论】:
-
发送请求到 'bittrex.com/api/v1.1/public/…' 而不是 'localhost:4200/api/getorderbook?market=${currency1}-${currency2}&type=both' 这里有什么困惑?
-
由于 CORS 原因,它不能以这种方式工作:无法加载 bittrex.com/api/v1.1/public//…:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'localhost:4200' 因此不允许访问。 所以我尝试使用代理