我正在进行保存操作,当数据无效时,响应是400 HTTP状态,其中包含JSON正文中的详细信息。我想阅读JSON所以我可以在下面显示它是我一直在使用的代码,但似乎没有任何工作可以获得400错误的身体响应
private _onSave() {
let e: EmployeeSaveEntity = this.state.employeeSave;
this._save(e, this._onResponse.bind(this) , this._onCheckError.bind(this));
}
public _save(employee: EmployeeSaveEntity, onFulfilled: any, onReject: any) {
let url: string = __URL__;
url += 'Employees';
let context: any = this;
let res: Promise<Response>;
try {
res = fetch(url,
{
//"cors" | "navigate" | "same-origin" | "no-cors"
//mode:"no-cors",
method: "POST",
headers: {
'Authorization': `Bearer ${context._authentication.token.access_token}`,
"Content-Type": "application/json"
},
body: employee.getJSON()
}).then(onFulfilled, onReject);
}
catch (error) {
throw new Error('Failed to save employee');
};
}
private _onCheckError(value: any) {
console.log('_onCheckError');
console.log(value);
}
private _onResponse(value: Response) {
console.log('_onResponse');
console.log(value);
console.log( value.text() );
value.json().then(this._onJson.bind(this), this._onCheckError.bind(this));
}
private _onJson(value: any) {
console.log('_onJson');
console.log(value);
}
HTTP / 1.1 400 Bad Request Cache-Control:no-cache Pragma:no-cache Transfer-Encoding:chunked Content-Type:application / json; charset = utf-8到期日:1日期:星期五,2017年10月20日14:50:33 GMT X-Response-From:10.50.46.29
{ “HierId”:[ “您无法在此层次结构级别将主表数据插入系统。” ] “PrimaryPhoneNumberCountryCallingCode”: “当PrimaryPhoneNumber有值时,PrimaryPhoneNumberCountryCallingCode是必需的。” ] }
答案 0 :(得分:0)
由于HTTP请求成功(您有任何响应),结果将只传递给onFulfilled
方法。
看看这个例子:
fetch("/error").then((response) => {
console.log(response.status); //400 in your case
response.json().then((errorJson) => {
console.log(errorJson); // should return the error json
});
})