Reputation: 6527
I'm wondering how to send an HTTP post request without a body (specifically in Angular). Here's what I'm doing now, but I'm getting the error Expected 2-3 arguments, but got 1)
.
I realize the second argument is for the body, but I'm not sending that to the server (yes, I understand that a POST call changes the state of a system and have looked into THIS question).
postRequest(id) {
this.http.post('/api?data=' + id).map(
(response) => {
return response;
}
)
}
Upvotes: 44
Views: 61333
Reputation: 11
Cannot comment the accepted answer, so I'll just add that passing null is not sufficient, because the content type will not be inferred correctly and you may receive a 415 (at least that was my case). Use the options on http.post to specify the content type in the header and force json with the null body
this.http.post<T>(url, null, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
Upvotes: 1
Reputation: 51
If request body is not there for post or put method then send empty object to request. ex: {}.
Upvotes: 1
Reputation: 4414
If null
is not working (4XX error client side), try with {}
JSON:
postRequest(id) {
this.http.post('/api?data=' + id, {}).map((response) => {return response;});
}
Upvotes: 6
Reputation: 1040
Try to call HTTP 'Post' without passing a 'body', and got this error in Angular 6 -
If we go to definition of POST method in client.d.ts
, it shows that post method required either 'body' or 'null' value (e.g. - body: any | null)-
post(url: string, body: any | null, options?: {
...
}): Observable<Object>;
Solution - I just added 'null' and the error gone -
postSync(): any {
return this.http.post(`${environment.apiUrl}/xyz/sync-api`, null);
}
Upvotes: 3
Reputation: 41
Go to definition of POST method using your IDE and you can see passing either body: any | null
are the available inputs
post(url: string, body: any | null, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
Upvotes: 4
Reputation: 6527
Looks like this is the appropriate answer:
postRequest(id) {
this.http.post('/api?data=' + id, null).map(
(response) => {
return response;
}
)
}
Upvotes: 57