Sebastian Olsen
Sebastian Olsen

Reputation: 10878

How do I POST JSON in Angular 2?

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:

enter image description here

So instead of sending actual json, it just sends "[object Object]". Instead of "Request payload" it should be "JSON". What am I doing wrong?

Upvotes: 30

Views: 109835

Answers (3)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657068

The header should be

'Content-Type': 'application/json'

and

 body: data

should be

 body: JSON.stringify(data);

Upvotes: 1

Arnaud P
Arnaud P

Reputation: 12607

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:

Inlined

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

Extendable class

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}
    )
  }

The gist

In the beginning I missed this sort of 'nested' way to pass in the content-type:

{headers:{'Content-Type': 'application/json'}}

Upvotes: 24

Ankit Singh
Ankit Singh

Reputation: 24945

You need to stringify the payload

var requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: this.apiURL + url,
            headers: headers,
            body: JSON.stringify(data)
        })

Upvotes: 17

Related Questions