对于这个项目,我只是学习和练习Angular2。我没有服务器端,并且正在向barchart ondemand api发出API请求 。
我想知道是否有可能绕过cors问题。我对这一切仍然很陌生,因此非常感谢您对婴儿进行操作!我正在使用http://localhost:8080
。
错误消息:(api键已注释掉)
XMLHttpRequest cannot load http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&symbol=GOOG&type=daily&startDate=20150311000000. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
StockInformationService:
import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
@Injectable()
export class StockInformationService {
private apiRoot = "http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&";
constructor (private _http: Http) {}
getData(symbol: string): Observable<any> {
// Tried adding headers with no luck
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');
return this._http.get(this.apiRoot + "symbol=" + symbol + "&type=daily&startDate=20150311000000", {headers: headers})
.map(response => response.json());
}
}
应用组件:
import {Component} from "angular2/core";
import {VolumeComponent} from '../../components/volume/volume';
import {StockInformationService} from '../../core/stock-information.service';
@Component({
selector: 'app-shell',
template: require('./app-shell.html'),
directives: [VolumeComponent],
providers: [StockInformationService]
})
export class AppShell {
constructor(private _stockInformationService: StockInformationService) {}
// In my template, on button click, make api request
requestData(symbol: string) {
this._stockInformationService.getData(symbol)
.subscribe(
data => {
console.log(data)
},
error => console.log("Error: " + error)
)}
}
}
在我的控制台中,requestData错误:
Error: [object Object]
大多数情况下,这种情况是由于服务器的响应类型无效而发生的。
请确保以下2避免此问题。