Angular 15中如何向DELETE API请求体传递ID数组?
解决Angular 15 DELETE请求传递ID数组的媒体类型错误问题
你的代码报错原因是Angular的HttpClient.delete()方法第二个参数并非直接传请求体,而是需要传入配置选项对象,且未指定正确的请求头导致后端无法识别请求体格式。
修正步骤:
- 将ID数组放入配置选项的
body属性中 - 添加
Content-Type: application/json请求头,明确告知后端请求体格式
修正后的代码:
import { HttpClient, HttpHeaders } from '@angular/common/http'; // ... deleteProduct(productId: number): Observable<any> { // 构造要传递的ID数组(单个ID转为数组,支持批量删除可直接传数组参数) const idArray = [productId]; // 配置请求选项:指定请求体和请求头 const options = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), body: idArray }; return this.http .delete(`${this.baseUrl}api/Product/deleteproduct`, options) .pipe(map(data => data)); }
扩展:支持批量删除的版本
如果需要一次删除多个ID,可修改方法参数为数组:
deleteProducts(productIds: number[]): Observable<any> { const options = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), body: productIds }; return this.http .delete(`${this.baseUrl}api/Product/deleteproduct`, options) .pipe(map(data => data)); }
这样后端就能正确接收到JSON格式的ID数组,解决媒体类型不支持的错误。
内容的提问来源于stack exchange,提问作者HarrY
相关产品推荐
相关产品推荐

