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
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(..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With