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

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

问题描述

错误如下:

XMLHttpRequest 无法加载 http://some_url.herokuapp.com/api/some_api/.请求的资源上不存在Access-Control-Allow-Origin"标头.Origin 'http://localhost:3000' 因此不允许访问.响应的 HTTP 状态代码为 503.

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.

打电话时

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 needs to return an Access-Control-Allow-Origin header in its response.

在原始请求中发送 Origin 标头将启用服务器端的 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 it detects that the domain of the request isn't the same as the caller's.

在服务器端实现预检选项请求时要小心,因为证书不在此级别发送.它们仅在目标请求中发送.这似乎是问题,因为您有 503 错误.您正在尝试检查 OPTIONS 请求是否经过身份验证,但实际上并非如此...

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

查看这篇文章了解更多详情:

See this article for more details:

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

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