I don't understand what I am doing wrong, my server returns "undefined" when I try to get the json.
POST(url, data) { var headers = new Headers(), authtoken = localStorage.getItem('authtoken'); headers.append("Content-Type", 'application/json'); if (authtoken) { headers.append("Authorization", 'Token ' + authtoken) } headers.append("Accept", 'application/json'); var requestoptions = new RequestOptions({ method: RequestMethod.Post, url: this.apiURL + url, headers: headers, body: data }) return this.http.request(new Request(requestoptions)) .map((res: Response) => { if (res) { return { status: res.status, json: res.json() } } }); }
And my function:
login(username, password) { this.POST('login/', {test: 'test'}).subscribe(data => { console.log(data) }) }
When I try this, the request body looks like this:
So instead of sending actual json, it just sends "[object Object]". Instead of "Request payload" it should be "JSON". What am I doing wrong?
POST requestsIn Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request.
To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.
It is a bit awkward requirement since Angular is JavaScript framework and It does not accept post request because post request needs to be handled at server side only not at client side.
HttpClient. post() method is an asynchronous method that performs an HTTP post request in Angular applications and returns an Observable. HttpClient. post() has a type parameter similar to the HttpClient. get() request, through which we can specify the expected type of the data from the server.
I have been looking for a visual answer to the question of posting json data in Angular for a while, to no avail. Now that I eventually have something working, let's share:
Let's assume you expect a json response body of type T
.
const options = {headers: {'Content-Type': 'application/json'}}; this.http.post<T>(url, JSON.stringify(data), options).subscribe( (t: T) => console.info(JSON.stringify(t)) );
Official doc
import { HttpClient, HttpHeaders } from '@angular/common/http'; export class MyHttpService { constructor(protected http: HttpClient) {} headers = new HttpHeaders({ 'Content-Type': 'application/json' }); postJson<T>(url: string, data: any): Observable<T> { return this.http.post<T>( url, JSON.stringify(data), {headers: this.headers} ) }
In the beginning I missed this sort of 'nested' way to pass in the content-type:
{headers:{'Content-Type': 'application/json'}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With