Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrade Http to HttpClient in Angular 5: "server responded with a status of 415 (Unsupported Media Type)"

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

like image 255
mrapi Avatar asked Jan 30 '23 05:01

mrapi


2 Answers

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(..

like image 117
gjz Avatar answered Feb 05 '23 17:02

gjz


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.

like image 38
Nut Leelawattananun Avatar answered Feb 05 '23 17:02

Nut Leelawattananun