在Angular 2应用程序中没有'Access-Control-Allow-Origin'标题 [英] No 'Access-Control-Allow-Origin' header in Angular 2 app

查看:4741
本文介绍了在Angular 2应用程序中没有'Access-Control-Allow-Origin'标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个项目,我只是学习和练习Angular 2.我没有服务器端,并向API请求
barchart ondemand api



我想知道是否可以绕过cors问题。我还是相当新的所有这一切,所以宝贝一步的说明真的很感激!我使用 http:// localhost:8080



错误讯息:(api key commented out) / p>

XMLHttpRequest无法加载http://marketdata.websol.barchart.com/getHistory.json?key=MY_API_KEY&symbol=GOOG&type=daily& ; startDate = 20150311000000。对预检请求的响应不通过访问控制检查:在请求的资源上没有Access-Control-Allow-Origin头。因此不允许访问原始'http:// localhost:8080'。



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> {
//尝试添加没有运气的标头
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} fromangular2 / 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]
})
导出类AppShell {
constructor(private _stockInformationService:StockInformationService){}

//我的模板,按钮点击,使api请求
requestData(符号:字符串){
this._stockInformationService.getData(symbol)
.subscribe(
data => {
console.log(data)
},
error => console.log(Error:+ error)
)}
}
b $ b}



在我的控制台中,requestData错误:
错误:[object Object]

解决方案

href =http://www.html5rocks.com/en/tutorials/cors/> http://www.html5rocks.com/en/tutorials/cors/ 。



你的资源方法不会被命中,所以他们的头部永远不会被设置。原因是在实际请求之前有一个预检请求,这是一个OPTIONS请求。所以错误来自预检请求不产生必要的头。
检查您是否需要在您的.htaccess文件中添加以下内容:

 头设置Access-Control-原点*


For this project, I'm just learning and practicing Angular 2. I have no server-side and am making API requests to barchart ondemand api .

I'm wondering if it is possible to bypass the cors issue. I'm still fairly new to all this, so baby-step instructions are really appreciated! I'm using http://localhost:8080.

Error message: (api key commented out)

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());
    }
}

App Component:

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)
            )}
    }

}

In my console, the requestData Error: Error: [object Object]

解决方案

You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.

Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers. check that you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

这篇关于在Angular 2应用程序中没有'Access-Control-Allow-Origin'标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆