【问题标题】:HttpClient POST with HttpParams带有 HttpParams 的 HttpClient POST
【发布时间】:2021-06-18 00:08:52
【问题描述】:

我正在尝试 POST 到要求将参数作为查询字符串参数而不是通过 POST 正文传递的端点。

const params = new HttpParams()
  .set('param1', '1')
  .set('param2', '2');

const url = environment.apiUrl + 'Service/Endpoint';

return this
  .httpClient
  .post<ServiceResponse>(url, { params })
  .pipe(map(res => res.httpStatusCodeSuccess));

这将返回 404,因为调用不包含任何查询字符串参数。我通过查看网络调用验证了这一点。

如果我使用.get(),但对 POST 端点使用 .post() 时,同样的代码确实对我有效。

我错过了什么?

【问题讨论】:

  • 您确定端点的配置符合您的预期吗?当您使用curl 命令或 Postman 进行测试时,您是否能够获得预期的行为?
  • @Pytth 如果我将其称为Service/Endpoint?param1=1&amp;param2=2,它可以在邮递员中使用

标签: angular typescript angular-httpclient


【解决方案1】:

post 的第二个参数是您要在请求中发送的 http 正文。如果没有正文,则将 null 传递给参数。然后将参数作为调用的第三个参数传递。

  .post<ServiceResponse>(url, null, { params: params })

get 具有不同方法签名的原因是您不能通过 http get 调用传递 http 正文。

【讨论】:

    【解决方案2】:

    我认为这是因为您将参数作为对象传递。

    参考下面的例子

    const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')

    让 body = new HttpParams();

    body = body.set('username', USERNAME);

    body = body.set('password', PASSWORD);

    http .post('/api', 正文, { 标头:我的标头), })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 2014-05-20
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多