在Angular 5中将Http升级到HttpClient:“服务器响应状态为415(不受支持的媒体类型)". [英] Upgrade Http to HttpClient in Angular 5: "server responded with a status of 415 (Unsupported Media Type)"
问题描述
我已经将应用程序从Angular 4.2升级到了5,但是将Http
更改为HttpClient
后,POST请求出现了错误:
I've upgraded an app from Angular 4.2 to 5 but after changed Http
to HttpClient
got error on POST request:
错误,服务器响应状态为415(不受支持的媒体 类型)
error the server responded with a status of 415 (Unsupported Media Type)
在app.module
中,我已导入HttpClientModule
:
import { HttpClientModule } from '@angular/common/http';
旧代码:
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);
}
新代码:
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
}
谢谢
推荐答案
对我来说,使用对象作为正文而不是对其进行字符串化时,它无需设置Content-Type标头即可工作.我猜想,使用字符串作为正文会使Angular假设将'text/plain'作为内容类型,而不是默认的'application/json'.
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(..
这篇关于在Angular 5中将Http升级到HttpClient:“服务器响应状态为415(不受支持的媒体类型)".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!