【发布时间】:2018-03-24 12:42:12
【问题描述】:
我希望每个人都做得很好。我最近开始使用 angular 4.4,我一直在尝试将数据发布到我的 api 服务器,但不幸的是它不起作用。我已经花了大约 2 天的时间,但仍然没有成功。并且已经尝试过来自angular.io 的 6-7 篇文章。 我已经尝试过 Http 和 Httpclient 模块 但似乎没有任何效果。
问题是,每当我尝试将数据发布到我的服务器时,Angular 都会发出 http OPTIONS 类型的请求,而不是 POST。
this.http.post('http://myapiserver.com', {email: 'adam@example.com'}).subscribe(
res => {
const response = res.text();
}
);
我也尝试发送自定义选项和请求,但仍然没有成功。
const headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded' });
const options = new RequestOptions({ headers: headers });
options.method = RequestMethod.Post;
options.body = {name: 'Adam Smith'};
//options.body = JSON.stringify({name: 'Adam Smith'}); // i also tried this
//options.body = 'param1=something¶m2=somethingelse'; // i also tried this
我使用的是 ASP.NET core 2.0,但由于它不起作用,我也尝试了简单的 php 代码,这是 php 的服务器端代码。而且它也不起作用。
<?php
print_r($_POST);
?>
注意:服务器上也启用了 Cors。另外,我还尝试了简单的获取请求,它的工作非常好。
非常感谢您的帮助。
提前致谢
【问题讨论】:
-
OPTIONS 是飞行前检查请求,如果一切正常,它将在之后进行 POST。您确定 CORS 配置正确吗?你看到了什么输出,你能用minimal reproducible example扩展“不工作”吗?
-
您是否从 OPTIONS 响应中得到任何奇怪的响应/标头?
-
这是发送pasteboard.co/GOBkz3Z.png的请求角度,响应为空Array()(因为我在服务器端(php)使用print_r($_POST)。
标签: javascript angular http-post angular-http angular-httpclient