typescript Angular 中没有正文的HTTP Post

qv7cva1a  于 2023-01-31  发布在  TypeScript
关注(0)|答案(5)|浏览(135)

我想知道如何发送一个没有正文的HTTP post请求(特别是在Angular中)。下面是我现在正在做的,但是我得到了错误Expected 2-3 arguments, but got 1)
我意识到第二个参数是用于主体的,但我没有将其发送到服务器(是的,我理解POST调用会更改系统的状态,并已研究了THIS问题)。

postRequest(id) {
  this.http.post('/api?data=' + id).map(
    (response) => {
      return response;
    }
  )
}
uhry853o

uhry853o1#

看起来这才是合适的答案:

postRequest(id) {
  this.http.post('/api?data=' + id, null).map(
    (response) => {
      return response;
    }
  )
}
ne5o7dgx

ne5o7dgx2#

如果null不工作(4XX错误客户端),请尝试使用{} JSON:

postRequest(id) {
    this.http.post('/api?data=' + id, {}).map((response) => {return response;});
}
acruukt9

acruukt93#

使用IDE转到POST方法的定义,您可以看到传递body: any | null是可用的输入

post(url: string, body: any | null, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
pokxtpni

pokxtpni4#

尝试在不传递“body”的情况下调用HTTP“Post”,在Angular 6中出现此错误-

如果我们转到**client.d.ts**中POST方法的定义,它显示POST方法需要“body”或“null”值(例如- body:任何|无效)-

post(url: string, body: any | null, options?: {
...
}): Observable<Object>;

**解决方案-**我刚刚添加了'null',错误就消失了-

postSync(): any {
    return this.http.post(`${environment.apiUrl}/xyz/sync-api`, null);
}
ne5o7dgx

ne5o7dgx5#

如果post或put方法的请求主体不存在,则向request.ex发送空对象:{}.

相关问题