在Angular 5中将Http升级到HttpClient:“服务器响应状态为415(不支持的媒体类型)”

时间:2017-11-14 18:09:16

标签: angular angular2-http angular-httpclient

我已将应用程序从Angular 4.2升级到5但在将Http更改为HttpClient后,POST请求出错:

  

错误服务器响应状态为415(不支持的媒体   型)

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
    }

感谢

2 个答案:

答案 0 :(得分:4)

对我而言,当使用对象作为正文而不是字符串化时,它没有设置Content-Type标题。我想使用字符串作为正文使得Angular假设&text; / plain&#39;作为内容类型而不是默认的&#39; application / json&#39;。

因此,不要使用新代码:

return this._http.put(url + id, model).subscribe(..

答案 1 :(得分:2)

它对我有用,方法是在发送给服务之前检查从输入类型接收到的数据类型。就我而言,我从带有字符串的下拉列表中获得了“ Id”。 因此,我使用parseInt将数据类型更改为数字,然后它起作用了。