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

心不动则不痛 提交于 2019-12-06 04:55:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!