发布 HttpClient 返回 body 为 null 或 body 为 object



尝试使用HttpClient发布数据时,我遇到了两个不同的错误:

  1. 由于booking是一个对象,我得到了Backend returned code 400, body was: [object Object].
  2. 使用JSON.stringify(booking)我得到Backend returned code 415, body was: null.

怎么会这样?

public addBooking(booking): Observable<any[]> {
return this.http.post<any[]>(`${this.url}bookings`, booking)
.pipe(
catchError(this.handleError)
);
}

对象在招摇作品中使用以下作为测试对象。

{
"firstDate": "2020-05-29",
"secondDate": "2020-05-29",
"productId": 0,
"userId": 0
}

尝试添加Content-TypeAccept标头。

import {HttpHeaders} from '@angular/common/http';
public addBooking(booking): Observable<any[]> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
})
};
return this.http.post<any[]>(`${this.url}bookings`, booking, httpOptions)
.pipe(
catchError(this.handleError)
);
}

看起来,您的数据无效,因为 400 是错误请求。此外,您的服务器会用[Object object]响应错误,因此我建议您必须在服务器上使用类似JSON.stringify的 smth 来响应正确的错误文本

问题要么是因为您没有将标头中的"内容类型"设置为"应用程序/json"。否则,问题可能是因为"booking"实际上不是包含上述数据的JSON。

注意:请提及您要发送到 API 的数据(以及响应(

最新更新