首页 > 解决方案 > 在主 html 文件本身中显示 NodeJS 错误

问题描述

我使用 NodeJs 制作了一个表单,我对输入进行了一些验证,当用户输入错误的值时会显示错误,这里的问题是错误出现在新的空白页面上,但我需要错误出现在主 html 文件本身上很酷这里的造型是现场网站http://mido.sundays.org.uk

我试图在同一条路线上发出发布请求,以查看错误是否会出现在同一页面上,但页面变成了白色的空白页面,里面有文字

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>`);
    })
  });

我所需要的只是在同一页面中显示错误并阻止提交..

标签: javascripthtmlnode.js

解决方案


在提交表单之前,您是否有理由无法在前端进行验证?这通常是首选方式。您可以进行一些后端验证,这样您就不会将不良数据输入您的数据库,但是一旦您发送请求,您需要发送回响应,在您的情况下,响应是消息而不是整个 HTML 页面。您可以通过向提交按钮添加事件侦听器来创建验证,然后在验证后使用 Ajax 将数据发送到后端,或者您可以使用 Bootstrap 的内置验证,而不是仅仅通过表单操作来混淆 Ajax。https://getbootstrap.com/docs/4.0/components/forms/#validation


推荐阅读