简体   繁体   English

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

[英]Cannot read property 'username' of undefined error in chat app

This is error screen: 这是错误屏幕:

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)

I am trying to get user name from ejs file. 我正在尝试从ejs文件获取用户名。

This is server.js 这是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()); 
    }
});

This is html file: 这是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>

This is user.js 这是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);

This is my passport.js file 这是我的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);
            });
        });

}));

As per the error I see and your comment stating that the passport.js has the same code as passport-local.js file. 根据我所看到的错误,以及您的评论,指出passport.js具有与passport-local.js文件相同的代码。

You are using req.body.username but as per the error, either your req.body is undefined or the newUser is undefined. 您正在使用req.body.username,但根据错误,您的req.body未定义或newUser未定义。

Can you add console.log on the req.body for passport.js file and tell me what do you get? 您能在req.body上为password.js文件添加console.log并告诉我您得到了什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法读取未定义错误的属性“用户名” - Cannot read property 'username' of undefined error 无法读取未定义的属性“用户名” - Cannot read property 'username' of undefined 我收到错误“无法读取未定义的属性“用户名”” - I am getting the error "cannot read property "username" of undefined" 500内部服务器错误:无法读取未定义的属性“用户名” - 500 Internal Server Error: Cannot read property 'username' of undefined 错误类型错误:无法读取未定义 Ionic/Firestore 的属性“用户名” - ERROR TypeError: Cannot read property 'username' of undefined Ionic/Firestore Angular 错误类型错误:无法读取未定义的属性“用户名” - Angular ERROR TypeError: Cannot read property 'userName' of undefined FormComponent.html:8错误TypeError:无法读取未定义的属性&#39;userName&#39; - FormComponent.html:8 ERROR TypeError: Cannot read property 'userName' of undefined 错误无法读取未定义 Express 应用程序的属性 - Error cannot read property of undefined Express app SocketIO聊天-无法读取未定义的属性 - SocketIO Chat - Cannot read property of undefined “ typeError:无法读取未定义的属性“用户名”。” - “typeError: Cannot read property 'username' of undefined.”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM