2017-10-20 154 views
0

我正在進行保存操作,當數據無效時,響應是一個400 HTTP狀態,其中包含JSON主體中的詳細信息。我想讀的JSON,所以我可以顯示它下面是我一直使用的代碼,但似乎沒有任何上得到一個400錯誤的身體反應讀取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 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." ] }

+0

你是不是在發送你的頭'內容length'。這可能是一個問題。在RFC中,「應用程序應該使用這個字段來表示消息體的傳輸長度,除非4.4節中的規則禁止這樣做。」 –

+0

'application/json'確實不**有一個字符集。 –

+0

獲取內容長度不需要附加到標題。這一切都適用於數據正確的時候我得到了一個響應200返回一切正常。我真正想知道的是你如何閱讀錯誤請求的內容。 – user1730289

回答

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 
    }); 
}) 
+0

這與我使用的示例類似,但我的狀態爲0。我必須添加模式:「no-cors」,根據我的請求進一步獲取,然後收到以下消息** Uncaught(in承諾)語法錯誤:在EVAL輸入 意外結束(EVAL在./components/employee.tsx(app.5319b150089f3650765c.js:8370),:233:26) 在 ** – user1730289

+0

@ user1730289添加「模式:「 no-cors'「會告訴瀏覽器阻止您訪問響應的前端JavaScript代碼。 – sideshowbarker

+0

K但我不添加它我得到這個**無法加載https:// domain/Employees:沒有'Access-Control-Allow-Origin'標題出現在請求的資源上。因此不允許訪問Origin'https:// localhost:3000'。響應的HTTP狀態碼爲400.如果一個不透明的響應滿足您的需求,請將請求的模式設置爲'no-cors',以取消禁用CORS的資源。** – user1730289