无法读取属性'用户名'聊天应用中的未定义错误

时间:2018-05-24 02:46:47

标签: javascript node.js mongodb mongoose passport.js

这是错误屏幕:

express-session deprecated undefined
saveUninitialized option; provide saveUninitialized option
server.js:52:11 listening on port 3000 events.js:167
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'username' of undefined
    at User.findOne (C:\Users\aksha\Desktop\kik\passport\passport-local.js:42:32)
    at C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\model.js:4187:16
    at model.Query.Query._completeOne (C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\query.js:1479:12)
    at Immediate.Query.base.findOne.call (C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\query.js:1535:10)
    at Immediate.<anonymous> (C:\Users\aksha\Desktop\kik\node_modules\mquery\lib\utils.js:119:16)
    at runCallback (timers.js:696:18)
    at tryOnImmediate (timers.js:667:5)
    at processImmediate (timers.js:649:5) Emitted 'error' event at:
    at C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\model.js:4189:13
    at model.Query.Query._completeOne (C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\query.js:1479:12)
    [... lines matching original stack trace ...]
    at processImmediate (timers.js:649:5)

我正在尝试从ejs文件中获取用户名。

这是server.js

const express = require('express');
const bodyParser =require('body-parser');
const ejs = require('ejs');
const http = require('http');
const container = require('./container');
const cookieParser = require('cookie-parser');
const validator = require('express-validator');
const session = require('express-session');
const Mongostore = require('connect-mongo')(session);
const mongoose = require('mongoose');
const flash = require('connect-flash');
const passport = require('passport');

container.resolve(function(users) {

    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/footballkik',{useMongoClient: true});

    const app = SetupExpress();

    function SetupExpress(){

        const app = express();
        const server = http.createServer(app);
        server.listen(3000,function(){
            console.log('listening on port 3000');
        });

        ConfigrationExpress(app);

        //ROUTER SETUP
        const router = require('express-promise-router')();
        users.SetRouting(router);
        app.use(router);
    }




    function ConfigrationExpress(app) {

        require('./passport/passport-local');

        app.use(express.static('public'));
        app.use(cookieParser());
        app.set('view engine','ejs');
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({extended: true}));

        app.use(validator());
        app.use(session({

            secret:'thisisatest',
            resave: true,
            saveInitialized: true,
            store: new Mongostore({mongooseConnection:mongoose.connection})
        }))

        app.use(flash());
        app.use(passport.initialize());
        app.use(passport.session()); 
    }
});

这是html文件:

<!DOCTYPE html>

<html>
<head>

    <title>Xinfin Chat</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="/css/login.css">

</head>

<body>

    <div class="container logo-container">
        <div class="row">
            <div class="col-md-12">
                    <nav class="navbar" id="nav_bar" role="navigation">

                        <div class="navbar-header">
                            <button type="button" class="navbar-toggle navbar_icon" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                                <span class="sr-only">Toggle navigation</span> 
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                            <h1 class="logo-div">
                                <a href="/">Xinfin Chat</a>
                            </h1>
                        </div>



                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

                            <ul class="nav navbar-nav navbar-right">
                                <li style="padding-right: 50px;">
                                    <h2 class="reg-div">
                                        <a href="/">
                                            Login
                                        </a>
                                    </h2>

                                </li>


                                <li class="reg_link2">
                                    <h2 class="reg-div">
                                        <a href="/signup">
                                            Register
                                        </a>
                                    </h2>
                                </li>
                            </ul>
                        </div>

                    </nav>
                </div>

        </div>
    </div>

<div id="main">
    <div class="main">
        <form action="/signup" method="post">

            <h1>
                Register
            </h1>

            <div class="inset">
                <p>
                  <label for="username">USERNAME</label>
                  <input type="text" name="username" class="" placeholder="">
                </p>

                <p>
                    <label for="email">EMAIL ADDRESS</label>
                    <input type="text" name="email" placeholder="" />
                </p>
                <p>
                    <label for="password">PASSWORD</label>
                    <input type="password" name="password" placeholder="" />
                </p>

            </div>

            <p class="p-container">
                <span><a href="/">Login</a></span>
                <input type="submit" class="login-log" style=" background: #3bb5ec; border: #3bb5ec;" value="Register">
            </p>
        </form>
    </div>
</div>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


</body>
</html>

这是user.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');

    const userSchema = mongoose.Schema({

            username:{type: String, unique: true},
            fullname:{type: String, unique: true,default:''},
            email:{type: String, unique: true},
            password:{type: String, default:''},
            userImage:{type: String, default:'default.png'},
            facebook:{type: String, default:''},
            fbTokens:Array,
            goolge:{type: String, default:''},
            goolgeTokens:Array

    });

    userSchema.methods.encryptPassword = function(password) {
        return bcrypt.hashSync(password,bcrypt.genSaltSync(10),null);

    };

    userSchema.methods.validUserPassword = function(password) {
        return bcrypt.compareSync(password,this.password);

    }

    module.exports = mongoose.model('user',userSchema);

这是我的passport.js档案

'use strict';

const passport = require('passport');
const User = require('../models/user');
const LocalStrategy = require('passport-local').Strategy;


passport.serializeUser((user,done)=> {

    done(null, user.id);
});

passport.deserializeUser((id,done)=>{

    user.findById(id,(err,user)=>{

        done(err,user);

    });
});

passport.use('local.signup', new LocalStrategy({

    usernameField:'email',
    passwordField:'password',
    passReqToCallBack: true},(req,email,password,done)=>{

        User.findOne({'email':email},(err,user)=>{

            if(err){

                return done(err);
            }

            if(user){

                return done(null,false,req.flash('error','user email already exist'));
            }

            const newUser = new User();

            newUser.username = req.body.username;
            newUser.email= req.body.email;
            newUser.password=newUser.encryptPassword(req.body.password);

            newUser.save((err)=>{

                done(null,newUser);
            });
        });

}));

1 个答案:

答案 0 :(得分:0)

根据我看到的错误和您的评论,说明passport.js与passport-local.js文件具有相同的代码。

您使用的是 req.body.username ,但根据错误, req.body 未定义或者newUser未定义。

你可以在req.body上为passport.js文件添加console.log并告诉我你得到了什么?