使用 EJS 模板引擎在 Node.js 中提交表单后,我不断收到验证器错误

Posted

技术标签:

【中文标题】使用 EJS 模板引擎在 Node.js 中提交表单后,我不断收到验证器错误【英文标题】:I keep getting validator errors after submitting my form in Node.js using EJS templating engine 【发布时间】:2021-10-03 11:13:46 【问题描述】:

当我使用 Postman 发出请求时,代码运行良好且完美。但是每当我从前端发送相同的请求时,我都会收到此错误。

Result 
  formatter: [Function: formatter],
  errors: [
    
      value: undefined,
      msg: 'Please enter your name',
      param: 'name',
      location: 'body'
    ,
    
      value: '',
      msg: 'Please enter a valid Email',
      param: 'email',
      location: 'body'
    ,
    
      value: undefined,
      msg: 'Please enter a password with 6 or more characters',
      param: 'password',
      location: 'body'
    
  ]

这是我的 signup.ejs 文件。

<!doctype html>
<html lang="en">
  <%- include('./partials/header.ejs')%>
  <%- include('./partials/navbar.ejs')%>
  <body>
    <section class="form my-4 mx-5">
      <div class="container">
        <div class="row no-gutter">
          <div class="col-lg-5">
            <img src="/images/joyce-busola-Nnv0DHFG1Ds-unsplash.jpg" class="img-fluid">
          </div>
          <div class="col-lg-7 px-5 pt-5">
            <h1 class="font-weight-bold py-3">Queue's</h1>
            <h4>Register your new Account</h4>
            <form action="/user/register" method="POST">
              <div class="form-row">
                <div class="col-lg-7">
                  <input type="text" id="name" class="form-control my-3 p-3" placeholder="your name">
                </div>
              </div>

              <div class="form-row">
                <div class="col-lg-7">
                  <input type="email" id="email" class="form-control my-3 p-3" placeholder="email address">
                </div>
              </div>

              <div class="form-row">
                <div class="col-lg-7 input-group">
                  <input type="password" class="form-control my-3 p-3" id="password" placeholder="password">
                  <div class="input-group-addon my-3 p-3">
                    </a><i class="bi bi-eye-slash" id="togglePassword"></i>
                  </div>
                </div>
              </div>
            

              <div class="form-row">
                <div class="col-lg-7">
                  <button type="submit" class="btn1 mt-3 mb-5">Register</button>
                </div>
              </div>
              <a href="#">forgot password</a>
              <p>Already have an acount? <a href="/user/login">Login here</a></p>
            </form>
          </div>
        </div>
      </div>
    </section>
    <%- include('./partials/footer.ejs')%>  
  </body>
</html>

这是我的注册控制器对象的副本。

require('dotenv').config();
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const  createToken  = require('../middleware/auth_middleware');
const maxAge = 36000;
module.exports.register_post =  async (req, res) => 
  const  name, email, password  = req.body;
  // Searching if User already exists
  try 
    let user = await User.findOne( email );
    if(user) return res.status(400).json( errors : [ msg: "User already exists"],);

    // Create User Object
    user = new User( name, email, password );

    // Saving new User
    await user.save();

    // Creating User token with JWT 
    let payLoad = user._id;
 
    const prize = createToken(payLoad);
    res.cookie('jwt', prize, 
      httpOnly: true,
      maxAge : maxAge * 1000
    );

    res.status(201).json( 
      msg: `$user.email successfully registered`,
      name: user.name,
      email: user.email);  

      console.log(user, prize);
   
  catch (error) 
      console.log(error.message);
      res.status(500).send('Server error')
    ;    

我制作了一个中间件来使用 express-validator 处理验证。这是验证器文件。

require('dotenv').config()
const  check, validationResult  = require('express-validator');
const jwt = require('jsonwebtoken');
const maxAge = 36000;
const secret = process.env.JWT_SECRET;

const authValidator = () => 
  return [
  check('name', 'Please enter your name').not().isEmpty(),
  check('email', 'Please enter a valid Email').trim().isEmail(),
  check('password', 'Please enter a password with 6 or more characters').isLength(min:6)
];

const validateError = (req, res, next) => 
const errors = validationResult(req);
if(errors.isEmpty()) 
  return next()

const extractedErrors = [];
errors.array().map(err => extractedErrors.push( [err.param]: err.msg ))

console.log(errors);

return res.status(400).json( errors: extractedErrors )

这是注册路由器文件

const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const  authValidator, validateError  = require('../middleware/auth_middleware');

router.get('/login', userController.login_get );
router.post('/login', userController.login_post );

router.get('/register', userController.register_get );
router.post('/register', authValidator(), validateError, userController.register_post );

module.exports = router;

【问题讨论】:

【参考方案1】:

您的输入字段缺少name 字段。这就是在请求正文中找不到输入数据的原因。

例如对于电子邮件字段:

<div class="form-row">
   <div class="col-lg-7">
       <input type="email" name="email" id="email" class="form-control my-3 p-3" placeholder="email address">
    </div>
</div>

【讨论】:

以上是关于使用 EJS 模板引擎在 Node.js 中提交表单后,我不断收到验证器错误的主要内容,如果未能解决你的问题,请参考以下文章

Node.js ejs中文手册

一起学Node.js

无法让样式表与 node.js 的 ejs 一起使用

Node.js_express_服务器渲染页面 ejs

什么是最可靠和最流行的 Node.js 模板引擎? [关闭]

node.js 的页面渲染方法ejs