从Angular2应用程序发送http post请求时如何启用CORS
Posted
技术标签:
【中文标题】从Angular2应用程序发送http post请求时如何启用CORS【英文标题】:How to enable CORS when sending http post request from Angular2 app 【发布时间】:2017-06-19 08:18:43 【问题描述】:当我尝试发送 http 请求时,我收到了这个关于 CORS 的错误。
XMLHttpRequest cannot load 'sever-domain'.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'my-firebsase-hosted-app-domain' is therefore not allowed access.
然后我像这样为我的 http 请求设置标头。
let headers = new Headers(
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/x-www-form-urlencoded'
);
let options = new RequestOptions( headers: headers );
this.postRequestSub = this._http.post(this.url, body, options);
但是我还是出现同样的错误,这不是正确的解决方法吗?
【问题讨论】:
服务器需要配置CORS。 Angular 不参与其中。 您可以在客户端使用代理来处理它。 webpack.github.io/docs/webpack-dev-server.html#proxy 感谢您尽快回复我。你的意思是我可以通过正确设置这样的代理来处理这个错误,对吧? link 【参考方案1】:正如 Günter Zöchbauer 所说,
需要在服务器上配置CORS
这里有一个链接可以帮助您入门Enable CORS。
【讨论】:
谢谢!我会检查这个链接。以上是关于从Angular2应用程序发送http post请求时如何启用CORS的主要内容,如果未能解决你的问题,请参考以下文章
从 Angular 2 客户端到 Node.js 服务器的 HTTP POST 请求
angular2 http.post 方法抛出 typeerror 异常
ionic 2 angular 2 从 ion-select 中获取值以发送 http post