4

I've upgraded an app from Angular 4.2 to 5 but after changed Http to HttpClient got error on POST request:

error the server responded with a status of 415 (Unsupported Media Type)

in app.module I've imported HttpClientModule:

import { HttpClientModule } from '@angular/common/http';

Old code:

 post(url: string, model: any): Observable<any> {
        let body = JSON.stringify(model);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.post(url, body, options)
            .map((response: Response) => <any>response.json())
            .catch(this.handleError);
    }

new code:

put(url: string, id: number, model: any): Observable<any> {
        let body = JSON.stringify(model);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options: any = new RequestOptions({ headers: headers });
        return this._http.put(url + id, body, options)
            .catch(this.handleError);        //only removed .map
    }

thanks

3
  • 2
    You need to rework the options and headers objects, please check angular.io/guide/http#making-a-post-request Commented Nov 14, 2017 at 18:13
  • 3
    hi.indeed,seems working return this._http.post(url, body, { headers: new HttpHeaders().set('Content-Type', 'application/json') } ) Commented Nov 14, 2017 at 18:27
  • read the docs, carefully and complete Commented Nov 14, 2017 at 18:45

2 Answers 2

6

For me it worked without setting the Content-Type header when using an object as body instead of stringify-ing it. I guess that using a string as body makes Angular assume 'text/plain' as content type instead of the default 'application/json'.

So instead of your new code just use:

return this._http.put(url + id, model).subscribe(..

Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much for the hint. You are a real savior. :)
2

It worked for me by checking the data type that is received from input type before being sent to service. In my case, I got "Id" from the dropdown list with string. So, I used parseInt to change data type to number and then it worked.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.