问题
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
回答1:
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(..
来源:https://stackoverflow.com/questions/47292568/upgrade-http-to-httpclient-in-angular-5-server-responded-with-a-status-of-415