【发布时间】:2016-06-30 08:58:42
【问题描述】:
对于这个项目,我只是在学习和练习 Angular 2。我没有服务器端并且正在向 API 请求 barchart ondemand 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.
库存信息服务:
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]
【问题讨论】:
-
您能添加您使用的服务器吗?这不是 angular2 错误,而是服务器的 CORS 配置有问题,如果您说您使用的是什么服务器(apache、node+express 等),您可以获得更具体的响应。我可以用 node+express 的服务器解决这个错误
-
这个答案可能有用:stackoverflow.com/a/58064366/7059557
-
这听起来可能很奇怪,但我不必在服务器端进行任何更改。 angular ui 项目有两个分支,一个正在处理另一个它不是。我还没有找到确凿的答案。
标签: angular webpack header cors