代码之家  ›  专栏  ›  技术社区  ›  Mr.H.

角度HttpClient在POST中使用URL参数

  •  1
  • Mr.H.  · 技术社区  · 6 年前

    今天我试图发送一个类似这样的post请求。 http://host/start?time=123456789 使用以下代码:

        const url = `/start`;
        const myParams = new HttpParams().set('time', toTimestamp(time).toString());
        return this.http.post(url, { headers: this.getHttpHeaders(), params: myParams }));
    

    http://host/start . 参数是在请求主体内部发送的。API不接受这一点,也不允许我更改API。如何更改代码以将参数包含在URL中?

    谢谢你的帮助。

    2 回复  |  直到 6 年前
        1
  •  1
  •   AT82    6 年前

    正如Sanyam提到的,post请求看起来像。。。

    http.post(url, data, httpOptions)
    

    所以在你的请求中你缺少了身体的真实部分。。。因为这是一个 POST 要求由于您无法控制API,因此可以添加 null 对于 body 部分

    return this.http.post(url, null, { headers: this.getHttpHeaders(), params: myParams }));
    
        2
  •  0
  •   Sanyam Goel    6 年前

    当你这样做的时候

    return this.http.post(url, { headers: this.getHttpHeaders(), params: myParams }));
    

    您正在请求正文中发送参数,这是此处所期望的

    1. GET将URL中的数据发送到服务器,以便从资源获取数据
    2. 资源

    在您的请求中遵循以下顺序:

     http.post(url, data, httpOptions)