【问题标题】:Angular HttpClient: Post method does not set parameter correctlyAngular HttpClient:Post 方法未正确设置参数
【发布时间】:2019-03-15 09:30:47
【问题描述】:

在我的方法transmitProject(project: ProjectModel): Observable<boolean> 中有一个通过HttpClient 的发布请求,我想将数据发布到我的后端:

-- 在我的transmitProject-方法中

const params = {
   projectId: project.projectId,
   description: documentation.description,
   // some other attributes ...
};

return this.http.post(this.conf.url, params).pipe(
   map(response => {
      console.log(response);
      return true;
   })
);

...直到这里一切正常。但是请求以 json 格式设置 post 数据。为了测试后端服务器,返回转储的 $_POST 变量 -> null。

请求负载: {projectId:“...”,描述:“...”,经度:10,纬度:10,... }

实际上应该是: projectId=...description=...longitude=10latitude=10...

-> 在 Postman 中一切正常。

【问题讨论】:

  • 在您的请求中尝试JSON.stringify(prams)
  • 以 JSON 传输数据是标准。你想让它们进行表单编码吗?

标签: angular ionic-framework rxjs httpclient


【解决方案1】:

这里的问题是Angular默认发送一个JSON类型的post请求。

您要么更改 PHP 后端,而是使用 $_POST 来读取 JSON:

<?
..
$JSON = file_get_contents("php://input");
if (!empty($JSON ))
{
  $params = json_decode($JSON, true); 
}
?>

或者,如果您真的想以x-www-form-urlencoded 转发发送 您可以使用 URLSearchParams 自动将内容类型设置为 application/x-www-form-urlencoded:

let body = new URLSearchParams();
body.set('username', username);
body.set('password', password);

this.http.post(this.loginUrl, body).map(...);

当然,如果你像这样正确编码你的身体,你也可以手动完成

let body = `username=${username}&password=${password}`;

但是您必须手动将标题设置为application/x-www-form-urlencoded

这样

this.http.post(this.loginUrl, body, { headers: headers }).map(...);

【讨论】:

  • 您好,谢谢。你能推荐一个更好的方法吗?这样一来,它听起来就像一个大杂烩。最先进的技术是什么?
  • 由于您使用的是 Angular,我建议使用 json 并如前所述更改后端,它简单易用。如果有帮助,如果您将其标记为答案,我将非常感谢。如果您还有其他问题,请询问:) 干杯
  • 你帮了我两个。无法通过标记来决定:-)
  • @xzesstence 查看您的活动页面,我看到您有一系列的反对意见。我认为您是单个用户的目标。您可以标记此答案并选择“需要主持人干预”并描述您的问题。
【解决方案2】:

这不是很明显,但你没有以正确的方式使用httpClient

您可以在this SO post 中找到这种情况的解释。

如果您不想使用 JSON 但想坚持使用x-www-form 编码,您的代码应如下所示:

const body = new HttpParams()
  .set('your property name', ** property value **)
  .set(...);

return this.http.post(this.conf.url,
  body.toString(),
  {
    headers: new HttpHeaders()
      .set('Content-Type', 'application/x-www-form-urlencoded')
  }
).pipe(... same code as you already have ...);

【讨论】:

  • 谢谢你,麦克风。你的方法是正确的方法吗?还是有更好的办法?
  • 我认为坚持使用 JSON 更为自然,因为它现在已成为广泛使用的标准。因此,如果您不需要 x-www-form,只需让 Angular 标准库与 content-type 成为 application/json 一起玩。这样,接收端就知道如何解码负载(JSON.decode,或类似的,取决于语言)。查看 HttpClient 上的 Angular 文档,例如:angular.io/guide/http
猜你喜欢
  • 2016-03-13
  • 2017-01-28
  • 2014-08-31
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
相关资源
最近更新 更多