You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

POST/PUT/GET接口正常,DELETE请求报415错误,求教设置Content-Type方法

解决DELETE请求返回415 Unsupported Media Type的问题

我之前也踩过这个坑!415错误本质是后端期望application/json类型的请求体,但你的DELETE请求没带上正确的Content-Type头,或者请求体格式不对。结合你给出的Angular项目代码片段,给你几个可行的解决办法:

方法1:手动给DELETE请求配置请求头与请求体

Angular的HttpClient.delete()默认不会自动设置Content-Type: application/json,也不会默认把参数序列化为JSON格式。你需要显式配置请求头,并且把要删除的manager对象作为请求体传入:

async deleteManager(manager) {
  try {
    // 构造JSON类型的请求头
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });
    // 发起DELETE请求,传入请求体和headers配置
    const response = await this.http.delete('/your-api-endpoint', {
      headers: headers,
      body: manager // 将manager对象作为请求体传递给后端
    }).toPromise();
    
    // 本地数据更新逻辑
    this.managerStore = this.managerStore.filter(m => m.id !== manager.id);
    this.managerSubject.next([...this.managerStore]);
    
    return response;
  } catch (error) {
    console.error('删除管理者失败:', error);
    throw error;
  }
}

方法2:全局拦截器统一处理所有DELETE请求

如果项目中有多个DELETE请求都遇到这个问题,可以写一个HTTP拦截器,自动给带请求体的DELETE请求加上Content-Type: application/json头:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class DeleteContentTypeInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 仅针对带请求体的DELETE请求添加头
    if (req.method === 'DELETE' && req.body) {
      const modifiedReq = req.clone({
        headers: req.headers.set('Content-Type', 'application/json')
      });
      return next.handle(modifiedReq);
    }
    return next.handle(req);
  }
}

记得在app.module.ts中注册这个拦截器:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { DeleteContentTypeInterceptor } from './delete-content-type.interceptor';

@NgModule({
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: DeleteContentTypeInterceptor,
      multi: true
    }
  ]
})
export class AppModule { }

额外排查要点

  • 确认后端是否要求DELETE请求必须携带请求体:有些后端接口设计会要求在请求体中传递删除资源的标识(比如ID),而非URL参数,这种情况下必须保证请求体格式与Content-Type匹配。
  • 检查是否有其他拦截器覆盖请求头:如果项目中存在其他HTTP拦截器,可能会覆盖你手动设置的Content-Type,需要排查拦截器的执行顺序和逻辑。

内容的提问来源于stack exchange,提问作者Evik Ghazarian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:31:26