【问题标题】:Angular 4 Http POST not workingAngular 4 Http POST 不起作用
【发布时间】:2018-03-24 12:42:12
【问题描述】:

我希望每个人都做得很好。我最近开始使用 angular 4.4,我一直在尝试将数据发布到我的 api 服务器,但不幸的是它不起作用。我已经花了大约 2 天的时间,但仍然没有成功。并且已经尝试过来自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 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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您是否尝试过将标头作为 post 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 导入标头

    【讨论】:

    • 是的,我已经尝试过了,它不起作用。而对于双重检查,我又试了一次,但它根本不起作用。它以 OPTIONS http 请求类型提交 ajax 请求。
    • 它完美地访问了服务器,但是当它应该是 POST 时使用了错误的 http 方法 OPTIONS。如果我运行上面的代码pasteboard.co/GOBkz3Z.png,请检查 Angular 发送的屏幕截图
    • 检查这个答案,可能会有所帮助! link
    • 我终于能够解决这个问题,非常感谢你们的帮助
    • 太棒了! - 您应该在有时间供将来参考时发布您的解决方案!
    【解决方案3】:

    我遇到了同样的问题,我就是这样使用的。(使用 FormData)试试吧。它对我有用。

    let formdata = new FormData();
    formdata.append('email', 'adam@example.com');
    
    this.http.post('http://myapiserver.com', formdata).subscribe(
        res => {
            const response = res.text();
        }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      相关资源
      最近更新 更多