【发布时间】:2021-10-07 23:21:49
【问题描述】:
我有一个应用程序,我需要通过 XMLHttpRequest 发送表单数据。当我发送该信息时,我需要验证表单,然后根据表单是否验证将信息发送回客户端。我正在使用 nodejs 和 express。
我的客户端代码是:
editor.save().then((output) => {
let formData = new FormData();
const xhr = new XMLHttpRequest();
formData.append('name', document.getElementById('inputProductName').value);
xhr.open('post', '/items/add', true);
xhr.send(formData);
}).catch((error) => {
console.error('Error: ' + error);
return;
}).finally(() => {
// This is where I need to retrieve the validation code and redirect accordingly.
if (success == false) {
window.location.href = '/items/add/failed';
} else {
window.location.href = '/items/add/success';
}
});
我的服务器端代码是这样的:
router.post('/add', (req, res) => {
let form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
if (fields.name.length < 1) { // If the name is empty
res.status(200).json({
success: false,
message: 'Product name must be specified'
});
} else {
res.status(200).json({
success: true,
message: 'Product added successfully'
});
}
});
});
所以如果验证失败,那么如果可能的话,我希望能够通过客户端获取成功和消息变量。
【问题讨论】:
-
你写的代码有什么问题?
-
我的客户端控制台出现错误,提示未定义成功。我最初只是想尝试使用 Flash 消息传递和 res.redirect,但它不起作用,这就是我在客户端重定向的原因。
-
为什么要定义
success?这是一个你无论如何都没有定义的变量。而且您正在向 XHR 发出请求,但从不查看响应。 (如果您仍然使用 Promise,为什么要使用 xhr 而不是 fetch?) -
我对 javascript 还很陌生,当我在 Google 上搜索发送表单数据时,xhr 是第一个出现的东西,所以我选择了它。我应该改用 fetch 吗?
标签: javascript node.js json express client