Fetch-api 发布表单数据时的错误处理
Fetch-api error-handling when posting form-data
我正在尝试构建单个 ReactJs
表单组件(以 TypeScript
编写,目标 ES6
),我将在我的网络应用程序中将其用于所有表单。
为了在发布表单时处理错误,我需要检查是否有错误。
这是我的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 help@me.please
这有助于用户识别出了什么问题?
稍后我想在服务器端验证失败(但客户端没有)的情况下实施一些处理,以便我可以向用户显示:Look. This value is wrong. Please fix.
。因此我确实需要保持一致。
我刚开始使用 fetch-api。也许这不是最好的选择?
你需要阻止表单的正常提交,一切都在JS中处理,否则你的页面会post默认将数据发送到你的服务器。
private handleSubmit = (ev: React.FormEvent<HTMLFormElement>): void => {
var theForm = ev.target as HTMLFormElement;
ev.preventDefault()
// ... your code
From MDN: The Event interface's preventDefault()
method tells the user
agent that if the event does not get explicitly handled, its default
action should not be taken as it normally would be.
我正在尝试构建单个 ReactJs
表单组件(以 TypeScript
编写,目标 ES6
),我将在我的网络应用程序中将其用于所有表单。
为了在发布表单时处理错误,我需要检查是否有错误。
这是我的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 help@me.please
这有助于用户识别出了什么问题?
稍后我想在服务器端验证失败(但客户端没有)的情况下实施一些处理,以便我可以向用户显示:Look. This value is wrong. Please fix.
。因此我确实需要保持一致。
我刚开始使用 fetch-api。也许这不是最好的选择?
你需要阻止表单的正常提交,一切都在JS中处理,否则你的页面会post默认将数据发送到你的服务器。
private handleSubmit = (ev: React.FormEvent<HTMLFormElement>): void => {
var theForm = ev.target as HTMLFormElement;
ev.preventDefault()
// ... your code
From MDN: The Event interface's
preventDefault()
method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.