415 (Unsupported Media Type)

hi I try postdata have been error 415 Unsupported Media Type :slight_smile:

  1. how to solve this case.
  2. how to add application/json on my typescript as below
    import { HttpClient, HttpHeaders } from ‘@angular/common/http’;

import { Injectable } from ‘@angular/core’;

import { environment } from ‘…/…/environments/environment’;


providedIn: ‘root’


export class HttpService {

headers = new HttpHeaders();

// options = { headers: this.headers, withCredintials: false };

options = { headers: this.headers };

constructor(private http: HttpClient) {}

post(serviceName: string, data: any) {

console.log("data asli:", JSON.stringify(data));

const url = environment.apiUrl + serviceName;

return this.http.post(url, JSON.stringify(data), this.options);



thank you

Well, as for what’s going on with the 415 error, you’d have to ask whoever administers wherever you’re posting it to, but I can say this: there is no need for manually calling JSON.stringify or making customHttpHeaders, and I think it’s a very important thing to never do unnecessary stuff for two major reasons:

  • it distracts from the important part of your code, making it harder to read;
  • it’s easy to inadvertently mess things up;

HttpClient is smarter than you give it credit for.

this.http.post<ReturnType>(url, data) works just fine.

Finally, this service adds no value as written. The point of services like this is to abstract something away. I try to make it so that client code only sees business level objects, so I want something like:

interface Customer {
  id: string;
  name: string;

class CustomerService {
  constructor(private http: HttpClient) {}

  allCustomers(): Observable<Customer[]> {
    return this.http.get<Customer[]>("/api/customers");

  customerById(id: string): Observable<Customer> {
    return this.http.get<Customer>(`/api/customer/${id}`);
  updateCustomer(cust: Customer): Observable<Customer> {
    return this.http.post<Customer>(`/api/customer/${id}`, cust);

The point here is that as far as outside this class is concerned, there is just a magical source of Customers. We don’t know that they’re coming over HTTP, we don’t care what methods are being used. Maybe there is an offline mode where these things come from on-device storage. Maybe it’s all mocked out and we’re getting fake data for testing. It is very important that all those sorts of changes can be made by only editing CustomerService. No clients of that class ever need to be affected.

1 Like

hi rapropos,
thank you for your reply.
my case is not yet to application/json but when I headers.append(Content-type’:‘application/json’);
but compiling had error.

Don’t do that. It’s not needed. When you pass HttpClient an object in the payload of a post call, it automatically deals with setting the Content-Type header.

1 Like