Angular 4 Http POST无效

时间:2017-10-12 14:16:17

标签: javascript angular http-post angular-http angular-httpclient

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

问题是,每当我尝试将数据发布到我的服务器时,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&param2=somethingelse'; // i also tried this

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

<?php
print_r($_POST);
?>

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

我真的很感激一些帮助。

提前致谢

4 个答案:

答案 0 :(得分:5)

我通过将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();

答案 1 :(得分:1)

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

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

确保从@ angular / http

导入标题

答案 2 :(得分:1)

我有同样的问题,我这样使用。(使用FormData)试试吧。它适合我。

let formdata = new FormData();
formdata.append('email', 'adam@example.com');

this.http.post('http://myapiserver.com', formdata).subscribe(
    res => {
        const response = res.text();
    }
);

答案 3 :(得分:0)

从'@ angular / common / http'导入{HttpClient,HttpHeaders}; 从'rxjs'导入{Observable};

saveGame(route,game):Observable<any>{

  let json = JSON.stringify(game);
        let params = 'json=' + json;

  let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
  return this.http.post(this.URL + route, params, { headers: headers });

}