在 Angular 5 中将 Http 升级为 HttpClient:“服务器响应状态为 415(不支持的媒体类型)" [英] Upgrade Http to HttpClient in Angular 5: "server responded with a status of 415 (Unsupported Media Type)"

查看:17
本文介绍了在 Angular 5 中将 Http 升级为 HttpClient:“服务器响应状态为 415(不支持的媒体类型)"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将应用程序从 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:

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

这篇关于在 Angular 5 中将 Http 升级为 HttpClient:“服务器响应状态为 415(不支持的媒体类型)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆