如何在Angular 2中启用CORS启用的HTTP请求? [英] How to make CORS-enabled HTTP requests in Angular 2?

查看:280
本文介绍了如何在Angular 2中启用CORS启用的HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误如下:


XMLHttpRequest无法加载 http://some_url.herokuapp.com/api/some_api/ 。在所请求的资源上没有Access-Control-Allow-Origin头。原因 http:// localhost:3000 因此不允许访问。

XMLHttpRequest cannot load http://some_url.herokuapp.com/api/some_api/. 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 503.

$ b

return this._http.post(requestUrl,JSON.stringify(requestBody),requestOptions)

return this._http.post(requestUrl, JSON.stringify(requestBody), requestOptions)

我遇到了麻烦CORS(当使用 Angular 1 )时,我记得,一旦CORS被激活服务器端,我不得不转换http请求来解析某些HTTP头

I had troubles with CORS (when working with Angular 1) in the past and I remember that once CORS were activated server-side,I had to transform the http request to parse certain HTTP headers.

我很困惑它应该如何工作,所以任何解释都是非常欢迎的。

I am quite confused about how it should work, so any explanation is very welcome.

推荐答案

事实上,它不是一个Angular2问题,但在服务器端的一个问题。预检OPTIONS请求需要在响应中返回 Access-Control-Allow-Origin 标头。

In fact, it's not an Angular2 issue but a problem at the server side. The preflighted OPTIONS request need to return a Access-Control-Allow-Origin header in its response.

原始头在原始请求中将启用服务器端的CORS支持。当我检测到请求的域不同于调用者时,浏览器会自动添加此标头。

Sending the Origin header in the original request will enable the CORS support on the server side. This header is automatically added by the browser when i detects that the domain of the request isn't the same than the caller one.

在实施预检OPTIONS请求时要小心因为凭证不会在此级别发送。它们只在目标请求中发送。它似乎是问题,因为你有503错误。您尝试检查OPTIONS请求是否已通过身份验证,但实际上并非如此...

By careful when implementing the preflighted OPTIONS request on the server side since credentials aren't send at this level. They are only send within the target request. It seems to be the problem since you have 503 error. You try to check if the OPTIONS request is authenticated but it's not actually the case...

有关详细信息,请参阅此文章:

See this article for more details:

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

这篇关于如何在Angular 2中启用CORS启用的HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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