尝试使用HttpClient发布数据时,我遇到了两个不同的错误:
- 由于
booking
是一个对象,我得到了Backend returned code 400, body was: [object Object]
. - 使用
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-Type
和Accept
标头。
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 的数据(以及响应(