我正在嘗試構建一個單一的ReactJs
表單組件(編寫在TypeScript
目標爲ES6
),我將用於我的web應用程序中的所有表單。 爲了在發佈表單時處理錯誤,我需要檢查是否有錯誤。發佈表單數據時提取api錯誤處理
這是我handleSubmit
方法:
private handleSubmit = (ev: React.FormEvent<HTMLFormElement>): void => {
var theForm = ev.target as HTMLFormElement;
const formData = new FormData(theForm);
fetch(theForm.action, { method: theForm.method, body: formData })
.then(response => {
if (!response.ok)
throw Error(response.statusText);
return response;
})
.catch(reason => console.log(reason));
}
我目前工作的行動是一個簡單的POST動作(例如):
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> Login(RequestAccountLoginPost request)
{
throw new ApplicationException("The application crashed in a way nobody expected. Sorry about that...");
}
然而,提交表單的時候,我總是最後是ASP.net標準錯誤頁面。 如何阻止此行爲並保留在表單顯示一些錯誤的頁面上There was an internal server-error. Write an e-mail to [email protected]
它可以幫助用戶確定出了什麼問題?
後來我想在服務器端驗證失敗的情況下執行一些處理(但客戶端沒有),所以我可以顯示用戶:Look. This value is wrong. Please fix.
。因此,我確實需要保持在同一頁面上。
我是使用fetch-api的新手。也許這不是最好的選擇呢?
我完全錯過了這個(因爲方法調用在'handleSubmit'內部),所以我甚至沒有想過原始事件。謝謝。會花費我很多時間來找出...;) – KingKerosin