我正在尝试构建一个单一的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