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

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

问题描述

对于这个项目,我只是在学习和练习 Angular 2.我没有服务器端,正在向barchart on demand api .

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 .

我想知道是否可以绕过 cors 问题.我对这一切还很陌生,所以非常感谢婴儿步骤说明!我正在使用 http://localhost:8080.

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.

错误信息:(api key 注释掉)

Error message: (api key commented out)

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'.

股票信息服务:

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 错误:错误:[对象对象]

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

推荐答案

这是服务器上 CORS 配置的问题.不清楚你用的是什么服务器,但是如果你用的是Node+express你可以用下面的代码解决

This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

该代码是@jvandemo 的答案 到一个非常相似的问题.

that code was an answer of @jvandemo to a very similar question.

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

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