Angular http post request content type from ‘text/plain’ to ‘application/json’

angularhttppostrequest

Im trying to get data from a service using POST request. But I cant change the headers (TS wont compile) or content type. I get this error in console:

status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'text/plain' not supported"

Below is my component code.

import { Component, OnInit } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  searchValue: any = '';

  constructor(private http: HttpClient) { }

  getData() {

    this.http.post('MY URL',
    JSON.stringify({
      "q": "Achmea"
    }))
    .subscribe(
    data => {
      alert('ok');
      console.log(data);
    }
    )

NB: Used the code snippet because the formatting wouldnt let me post as pre.

Using latest angular 4 version.
Also server should be correctly configured, accepting only json data.
I tried the examples from Angular docs but none of them worked.

Anyone have any idea how to get it working??
Thanks in advance.

Best Answer

In your example (and also in the comments) the two different http implementations which are provided by angular are mixed up. Since angular 4 HttpClient from '@angular/common/http' is available and is the recommended way to go. Since angular 5 the older Http from '@angular/http' is even marked as deprecated.

In order to prevent the exception message from your backend you have to set your headers in the following way:

const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.httpClient.post<T>(this.httpUtilService.prepareUrlForRequest(url), body, {headers: headers})
...

Please remove all dependencies from '@angular/http' in your code. As long as you are using objects from this modul you will have issues with your code.