Введите «пароль» формы возвращает неопределенный после синтаксического анализа с использованием экспресс bodyparser - PullRequest
0 голосов
/ 06 октября 2019

Я новичок в nodejs и проверяю форму в своем приложении nodejs. Но пароль, введенный в форму, возвращается как неопределенный тип после использования express bodyparser, и поэтому я не могу проверить пароли для регистрации. Как исправитьэта проблема и почему это происходит?

app.js

const express = require('express');
const expressLayouts = require('express-ejs-layouts'); 
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();

//DB config
require('dotenv').config(); //for setting environment variables on server
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{useNewUrlParser:true ,useUnifiedTopology: true})
    .then(() => console.log("mongodb connected"))
    .catch(err => console.log(err));


//EJS
app.use(expressLayouts);
app.set('view engine','ejs');

//Express Bodyparser
app.use(express.urlencoded({extended:true}));

//Routes
app.use('/',require('./routes/index'));
app.use('/users',require('./routes/users'));

const PORT = process.env.PORT || 5000;

app.listen(PORT,console.log(`Server started on port ${PORT}`));


views / register.ejs

<div class="row mt-5">
    <div class="col-md-6 m-auto">
      <div class="card card-body">
        <h1 class="text-center mb-3">
          <i class="fas fa-user-plus"></i> Register
        </h1>

        <form action="/users/register" method="POST">
          <div class="form-group">
            <label for="name">Name</label>
            <input
              type="name"
              id="name"
              name="name"
              class="form-control"
              placeholder="Enter Name"
              value="<%= typeof name != 'undefined' ? name : '' %>"
            />
          </div>
          <div class="form-group">
            <label for="email">Email</label>
            <input
              type="email"
              id="email"
              name="email"
              class="form-control"
              placeholder="Enter Email"
              value="<%= typeof email != 'undefined' ? email : '' %>"
            />
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input
              type="password"
              id="password"
              name="password"
              class="form-control"
              placeholder="Create Password"
              value="<%= typeof password != 'undefined' ? password : '' %>"
            />
          </div>
          <div class="form-group">
            <label for="password2">Confirm Password</label>
            <input
              type="password"
              id="password2"
              name="password2"
              class="form-control"
              placeholder="Confirm Password"
              value="<%= typeof password2 != 'undefined' ? password2 : '' %>"
            />
          </div>
          <button type="submit" class="btn btn-primary btn-block">
            Register
          </button>
        </form>
        <p class="lead mt-4">Have An Account? <a href="/users/login">Login</a></p>
      </div>
    </div>
  </div>

маршруты / пользователи.js

const express = require('express');
const router = express.Router();

//Login page
router.get('/login',(req,res)=>res.render('Login'));

//Register
router.get('/register',(req,res)=>res.render('register'));

//Registration Handling
router.post('/register',(req,res) =>{
    const { name, email, password1, password2 } = req.body;
    let errors = [];
    console.log(password1,typeof password1,name,typeof name);
    //Check required fields
    if(!name || !email ||!password1 || !password2){
        errors.push({msg:'Please fill required fields'});
    }

    //check if passwords equal
    if(password1 !== password2){
        errors.push({msg:'Passwords do not match'});
    }

    //check password length
    if(password1.length<6){
        errors.push({msg:'Password should be atleast 6 characters'});
    }

    if(errors.length>0){
        res.render('register',{
            errors,
            name,
            email,
            password1,
            password2
        });
    }else{
        res.send('pass');
    }
});

module.exports = router

консольный вывод

Server started on port 5000
mongodb connected
undefined undefined john doe string
TypeError: Cannot read property 'length' of undefined
    at G:\MERN Stack\NODE_PASSPORT_LOGIN\routes\users.js:28:18
    at Layer.handle [as handle_request] (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\layer.js:95:5)
    at next (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\layer.js:95:5)
    at G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:335:12)
    at next (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:174:3)
    at router (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:317:13)
    at G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:335:12)
    at next (G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:275:10)
    at G:\MERN Stack\NODE_PASSPORT_LOGIN\node_modules\express\lib\router\index.js:635:15
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...