Angular2中的CORS问题 [英] CORS ISSUE in Angular2

查看:275
本文介绍了Angular2中的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用webpack angular2入门套件( https://github.com/AngularClass/angular2- webpack-starter ),现在我遇到了一个问题。

I am using webpack angular2 starter kit (https://github.com/AngularClass/angular2-webpack-starter) for my application and now i have an issue.

我尝试拨打电话

getSomeData(): Observable<any> {
  let url =  here is my api URL;
  let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', "Access-Control-Allow-Origin": "*", 'dataType': 'json', });
  let options = new RequestOptions({ headers: headers });

  return this._http.get(url, options).map(res => res.json());
}

我有下一个错误


XMLHttpRequest无法加载(我的URL)对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问来源‘ http:// localhost:3000 。响应的HTTP状态代码为405。

XMLHttpRequest cannot load (my URL) 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:3000' is therefore not allowed access. The response had HTTP status code 405.

此Api(使用firebird)默认返回XML,这可能会引起问题。 / p>

This Api (It using firebird) returns XML by default, maybe this cause a problem.


  1. 如何使JSON始终出现?

  2. 如何使用CORS解决此问题?


推荐答案

此问题在服务器端。后者必须在HTTP调用的响应中返回 Access-Control-Allow-Origin 标头。

This issue is at the server side. The latter must return a Access-Control-Allow-Origin header in the response of the HTTP call.

大多数随着时间的流逝,您可以将一些工具插入服务器应用程序中以为您执行此操作。服务器知道当客户端发送 Origin 标头(由浏览器自动添加)时,必须返回CORS标头。

Most of time, there are tools you can plug into your server application to do this for you. The server knows that CORS headers must be returned when the client sends a Origin header (automatically added by the browser).

请参阅此文章以获取有关CORS的更多详细信息:

See this article for more details about CORS:

  • http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

这篇关于Angular2中的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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