node.js - 'req.body.username' 和 'req.body.password' 未定义

标签 node.js mongodb express mongoose body-parser

我正在我的项目中创建登录注册系统,实际上我在以前的许多项目中都做到了,但是这次我收到了一个错误,为此我看到了很多与此相关的帖子,但没有一个适用于我。

这是我的代码:

app.js

const express= require('express');
const mongoose= require('mongoose');
const bodyParser= require('body-parser');
const exphbs= require('express-handlebars');
const path= require('path');
const methodOverride= require('method-override');
const session= require('express-session');
const flash= require('connect-flash');


const app= express();
const port= process.env.PORT || 8000;

mongoose.Promise= global.Promise;
mongoose.connect(process.env.MONGODB_URI || 
'mongodb://localhost:27017/chat',{ useNewUrlParser: true });
app.use(express.static(path.join(__dirname, 'public')));

//body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

//View engine
app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');

//Load Routes
const index= require('./routes/index');

//Use routes
app.use('/',index);

app.listen(port,()=> {
    console.log(`Started on port ${port}`);
})

routes.index.js

const express = require('express');
const router = express.Router();
const bcrypt= require('bcryptjs');
const {User}= require('../models/User'); 


router.all('/*',(req,res,next)=> {
    req.app.locals.layout= 'layout';
    next();
})

router.get('/login',(req,res,next)=> {

    res.render('routes_UI/login');
})

router.get('/signup',(req,res,next)=> {

    res.render('routes_UI/signup');
})


router.post('/signup',(req,res)=> {

    let errors=[];

    if(req.body.password!==req.body.confirmPassword){
        errors.push({message:'Passwords do not match'});
    }

    if(errors.length>0){
        res.render('routes_UI/signup',{errors});
    }else{

        User.findOne({ username: req.body.username}).then((user)=> {
            if(user){
               req.flash('error_message',`A user with this username already exists`);
               res.redirect('/signup');
            }else{
                    bcrypt.genSalt(10, function(err, salt) {
                    bcrypt.hash(req.body.password, salt, function(err, hash) {

                        const user= new User({
                                username:req.body.username,
                                password:hash,
                            });

                        user.save().then(()=> {
                            req.flash('success_message',`You have 
registered successfully, please login`);
                            res.redirect('/login');
                        });                 
                     });
                  });
            }
        })   
    }   
})

module.exports = router;

View 文件夹中的routes_UI.signup.hbs

<div class="card card-register mx-auto mt-5">
    <div class="card-header">Register an Account</div>
    <div class="card-body">
        <form action="/signup" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label for="username">Username</label>
                <input name="username" class="form-control" id="username" type="text" aria-describedby="username" placeholder="Enter username">
            </div>
            <div class="form-group">
                <label for="exampleInputPassword1">Password</label>
                <input name="password" class="form-control" id="exampleInputPassword1" type="password" placeholder="Password">
            </div>
            <div class="form-group">
                <label for="exampleConfirmPassword">Confirm password</label>
                <input name="confirmPassword" class="form-control" id="exampleConfirmPassword" type="password" placeholder="Confirm password">
            </div>

            <button type="submit" class="btn btn-primary btn-block">Register</button>
        </form>
        <div class="text-center">
            <a class="d-block small mt-3" href="/login">Login Page</a>
            <a class="d-block small" href="/">Home Page?</a>
        </div>
    </div>
</div>

我得到的错误是-

(node:2468) UnhandledPromiseRejectionWarning: ValidationError: users 
validation failed: username: Path `username` is required., password: Path 
`password` is required.

at new ValidationError (C:\Users\DEEPAK\chat-app- 
1\node_modules\mongoose\lib\error\validation.js:30:11)

at model.Document.invalidate (C:\Users\DEEPAK\chat-app- 
1\node_modules\mongoose\lib\document.js:2064:32)

at p.doValidate.skipSchemaValidators (C:\Users\DEEPAK\chat-app- 
1\node_modules\mongoose\lib\document.js:1927:17)

at C:\Users\DEEPAK\chat-app-1\node_modules\mongoose\lib\schematype.js:896:9
at process._tickCallback (internal/process/next_tick.js:61:11)
(node:2468) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 
This error originated either by throwing inside of an async function 
without a catch block, or by rejecting a promise which was not handled with 
.catch(). (rejection id: 1)

(node:2468) [DEP0018] DeprecationWarning: Unhandled promise rejections are 
deprecated. In the future, promise rejections that are not handled will 
 terminate the Node.js process with a non-zero exit code.

用户模型

const mongoose= require('mongoose');

const UserSchema= new mongoose.Schema({

    username:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    }
})
const User= mongoose.model('users', UserSchema);

module.exports={User};

提前致谢

最佳答案

//body-parser
app.use(function(req, res, next) 
app.use(bodyParser.urlencoded({extended:true}));

上面的第一行代码不完整且不必要。要正确初始化主体解析器,您只需执行以下操作,如 documentation 中指出的那样。 .

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

关于node.js - 'req.body.username' 和 'req.body.password' 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915510/

相关文章:

node.js - Await 不适用于 Node.js 中的函数调用?

database - nodejs和数据库通信 - 如何?

mongodb - 将 Mongo shell 脚本转换为 SpringData/Java

node.js - MongoClient.connect - 错误: Could not locate any valid servers in initial seed list

javascript - NodeJs 快速 session 不保存 session

angular - 在 express 和 angular 之间共享接口(interface) interface/model 文件

node.js - heroku 服务器上的幽灵博客密码验证失败

node.js - Webpack @azure/storage-blob node-fetch AbortSignal 问题

node.js - 与 MongoDB 的单个连接还是多个连接更好?

javascript - 在 Node.js 中传播错误回调并避免所有额外的麻烦?