Angular 4 Http POST无效

Osa*_*ikh 6 javascript http-post angular-http angular angular-httpclient

我希望每个人都做得很好.我最近开始使用angular 4.4,我一直试图将数据发布到我的api服务器,但不幸的是它没有用.我花了两天时间,但仍然没有成功.并且已经尝试过6-7篇甚至来自angular.io的文章.我已经尝试了HttpHttpclient模块,但似乎没有任何工作.

问题是,每当我尝试将数据发布到我的服务器时,Angular都会生成http OPTIONS类型请求而不是 POST.

this.http.post('http://myapiserver.com', {email: 'adam@example.com'}).subscribe(
    res => {
        const response = res.text();
    }
);
Run Code Online (Sandbox Code Playgroud)

我也试图发送请求的自定义选项,但仍然没有成功.

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&param2=somethingelse'; // i also tried this
Run Code Online (Sandbox Code Playgroud)

我使用的是ASP.NET核心2.0,但由于它不起作用我也试过简单的PHP代码,这里是php的服务器端代码.它也没有用.

<?php
print_r($_POST);
?>
Run Code Online (Sandbox Code Playgroud)

注意:Cors也在服务器上启用.另外,我也试过简单的get请求,它的工作非常好.

我真的很感激一些帮助.

提前致谢

Osa*_*ikh 6

我通过将Content-Type设置为application/x-www-form-urlencoded:

  const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  const options = new RequestOptions({ headers: headers });
  const params = new URLSearchParams();
  params.append('mypostField', 'myFieldValue');
  http.post('myapiendpoint.com', params, options).subscribe();
Run Code Online (Sandbox Code Playgroud)


Jay*_*Ess 2

您是否尝试过将标头作为帖子中的第三个参数传递:

this.http.post('http://myapiserver.com', JSON.stringify({name: 'Adam Smith'}), { headers: new Headers({ 'Content-Type': 'application/json' }) }).subscribe(
    res => {
        const response = res.text();
    }
);
Run Code Online (Sandbox Code Playgroud)

确保从 @angular/http 导入标头