I am making a save operation that when the data is invalid the response is a 400 HTTP status with the details in the JSON body. I want to read the JSON so I can display it below is the code I have been using but nothing seems to work on getting a 400 error body response
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 Expires: -1 Date: Fri, 20 Oct 2017 14:50:33 GMT X-Response-From: 10.50.46.29
{"HierId":[ "You can not insert master table data into the system at this hierarchy level." ], "PrimaryPhoneNumberCountryCallingCode":[ "The PrimaryPhoneNumberCountryCallingCode is required when PrimaryPhoneNumber has a value." ] }
content-lengthin your headers. That may be an issue. From the RFC, "Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4." - Alex Wapplication/jsondoes not have a charset. - Antti Haapala