问题描述: 在使用 Angular 9 的 http.delete 方法时,可能会遇到返回“不支持的媒体类型 415”错误的问题。
解决方法: 通常,当使用 http.delete 方法时,我们不需要传递请求体。然而,Angular 默认会将请求头的 Content-Type 设置为 application/json,这可能会导致服务器返回“不支持的媒体类型 415”错误。
要解决此问题,我们需要手动将请求头的 Content-Type 设置为 text/plain,以告诉服务器我们不需要发送 JSON 数据。
下面是一个示例代码,演示如何解决这个问题:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class MyService {
constructor(private http: HttpClient) {}
deleteData(id: number) {
const options = {
headers: new HttpHeaders({
'Content-Type': 'text/plain'
})
};
return this.http.delete(`https://example.com/api/data/${id}`, options);
}
}
在上面的代码中,我们使用 HttpHeaders 类手动创建一个请求头对象,并将 Content-Type 设置为 text/plain。然后,将该请求头对象传递给 http.delete 方法的 options 参数中。
通过这种方式,我们可以解决“不支持的媒体类型 415”错误,并成功发送 delete 请求。