Angular 2 app中没有'Access-Control-Allow-Origin'标题

phi*_*yoo 46 header cors webpack angular

对于这个项目,我只是学习和练习Angular 2.我没有服务器端,并且正在向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());
    }
}
Run Code Online (Sandbox Code Playgroud)

应用组件:

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

}
Run Code Online (Sandbox Code Playgroud)

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

Pab*_*iel 38

这是服务器上CORS配置的问题.目前尚不清楚您使用的服务器,但如果您使用的是Node + express,则可以使用以下代码解决它

// 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();
});
Run Code Online (Sandbox Code Playgroud)

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

  • 嗨@LahiruGamage,`@CrossOrigin(exposedHeaders ="Access-Control-Allow-Origin")`在我的请求映射方法上工作. (4认同)
  • 如何在春季靴子@Ezequiel做到这一点? (2认同)

小智 17

您可以从这里阅读更多相关信息:http://www.html5rocks.com/en/tutorials/cors/.

您的资源方法不会被命中,因此它们的标题永远不会被设置.原因是在实际请求之前存在所谓的预检请求,这是OPTIONS请求.因此,错误来自于预检请求不会产生必要的标题.检查您是否需要在.htaccess文件中添加以下内容:

Header set Access-Control-Allow-Origin "*"
Run Code Online (Sandbox Code Playgroud)

  • 如果你不使用.htaccess fille怎么办? (15认同)
  • 由于您允许所有域控制您的后端,所以这个解决方案不是很糟糕吗?如果有人连接到您的服务器并在其上运行本地主机怎么办?他能够从你的后端获取所有数据。或者我错了,这是解决这个问题的安全且最佳的实践方法? (2认同)

Abn*_*ner 7

在使用http://www.mocky.io/时我也遇到了同样的问题.我所做的是添加mock.io响应头:Access-Control-Allow-Origin*

要添加它,只需要点击高级选项

Mock.io标题示例 完成此操作后,我的应用程序就能够从外部域检索数据.


Pra*_*amy 6

您只需将php文件设置为

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
Run Code Online (Sandbox Code Playgroud)


小智 6

我花了很多时间来解决问题,并最终通过在服务器端进行更改来解决。检查网站https://docs.microsoft.com/en-us/aspnet/core/security/cors

当我在服务器端启用 corse 时,它​​对我有用。我们在 API 中使用 Asp.Net 核心,下面的代码有效

1)Startup.cs的ConfigureServices中添加Addcors

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddMvc();
    }
Run Code Online (Sandbox Code Playgroud)

2) 在 Configure 方法中添加 UseCors 如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors(builder =>builder.AllowAnyOrigin());
        app.UseMvc();
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

我也遇到了同样的问题,并通过以下方式解决了这个问题。

步骤1:

$ npm install --save-dev http-proxy-middleware
Run Code Online (Sandbox Code Playgroud)

第2步:

在获取Web API时添加代理,如果您使用lite-server,则可以添加文件bs-config.js。

//file: bs-config.js
var proxyMiddleware = require('http-proxy-middleware');

module.exports = {
    server: {
        middleware: {
            1: proxyMiddleware('/example-api', {
                target: 'http://api.example.com',
                changeOrigin: true,
                pathRewrite: {
                '^/news-at-api': '/api'
                }
            })
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。