显示主要html文件本身中的NodeJS错误
我使用NodeJs制作了一个表单,我对输入进行了一些验证,当用户输入错误的值时显示错误,这里的问题是该错误出现在新的空白页面上,但是我需要该错误出现在主html文件本身上造型时尚这是实时站点
我试图在同一条路线上发出发帖请求,以查看错误是否会出现在同一页面上,但是该页面变成了白色空白页,里面有文字
app.post('/', function (req, res) {
const SchemaValidation = {
name: joi.string().min(4).required().error(() => {
return {
message: 'Name is required. (min:4 chars)',
};
}),
email: joi.string().email().error(() => {
return {
message: 'Email field can\'t be Empty',
};
}),
phone: joi.string().min(8).max(14).required().error(() => {
return {
message: 'Valid Phone number is Required (min:8 characters - max: 14 characters)',
};
}),
university: joi.string().required().error(() => {
return {
message: 'University Field is Required',
};
}),
faculty: joi.string().required().error(() => {
return {
message: 'Faculty Field is Required',
};
}),
academicyear: joi.string().required().error(() => {
return {
message: 'Academic Year Field is Required and should range from 1-6',
};
}),
workshop: joi.array()
.items(joi.string().error(() => {
return {
message: 'You Should pickup 2 Committees',
};
})),
first_choice: joi.string().required().error(() => {
return {
message: 'You should pickup first choice',
};
}),
second_choice: joi.string().required().error(() => {
return {
message: 'You should pickup second choice',
};
}),
};
joi.validate(req.body,SchemaValidation,(err, result) => {
if(err) {
res.send(`<p style='color:red; text-align:center; margin-top:20px;'>${err.details[0].message}</p>`);
return; // don't try saving to db if the schema isnt valid
}
else
res.send(`<p style='color:green; text-align:center; margin-top:20px;'>Successfully Posted Data</p>`);
})
});
我需要做的是在同一页面上显示错误并阻止提交。。
[我使用NodeJs制作了一个表单,我对输入进行了一些验证,当用户输入错误的值时显示错误,这里的问题是该错误出现在新的空白页面上,但是我需要显示错误...
回答如下:为了解决此问题,我强烈建议您使用Pug.js(模板引擎),因为您无法将参数传递到特定页面。通过使用模板引擎,您可以将数据作为对象传递,并使用res.render('index',{error:res.error.message})进行渲染。
您将能够从服务器端将显示您需要显示的错误对象的错误对象输出到页面中!