首页 > 解决方案 > 使用快速不响应的护照认证

问题描述

我正在尝试使用 nodejs 和 mongodb 使用护照身份验证,下面是我尝试过的代码,但没有得到任何响应。它甚至没有进入 findOrCreate 方法。

我正在使用nodejs v: 10.16.3npm v: 6.9.0

mongodb version:4.2.0和操作系统是MAC OS Mojave

这是依赖项列表-

"dependencies": {
    "body-parser": "^1.19.0",
    "connect-flash": "^0.1.1",
    "cookie-parser": "^1.4.4",
    "express": "^4.17.1",
    "express-session": "^1.16.2",
    "flash": "^1.1.0",
    "http": "0.0.0",
    "mongo": "^0.1.0",
    "mongodb": "^3.3.2",
    "mongoose": "^4.3.5",
    "mysql": "^2.17.1",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0"
  }

护照代码如下——

 app.post("/signup",(req,res)=>{
    console.log("Inside Signup",req.body);
    res.send(req.body);
    var emails=req.body.Email;
    console.log(emails);
    var names=req.body.Name;
    console.log(names);
    var passwords=req.body.Password;
   console.log(passwords);
    si(names,emails,passwords);
  });
 function si(username,email,password){
      passport.use('signup', new LocalStrategy({
        passReqToCallback : true
      },
      function(req, username, password, done) {
        findOrCreateUser = function(){
          // find a user in Mongo with provided username
    console.log("Step1 success");
          console.log(username);
          console.log(email);
          console.log(password);
          var dbo = db.db("record");
          dbo.collection("records").findOne({'Username':username}, function(err, result) {
            if (err){
              console.log('Error in SignUp: '+err);
              return done(err);
            }
            // already exists
            if (result) {
              console.log('User already exists');
              return done(null, false, 
                 req.flash('message','User Already Exists'));
            } else {
              var newUser = new User();
              newUser.Username = username;
              newUser.Password = password;
              newUser.Email = email;
              newUser.save(function(err) {
                if (err){
                  console.log('Error in Saving user: '+err);  
                  throw err;  
                }
                console.log('User Registration succesful');    
                return done(null, newUser);
              });
            }
          });
        };

        // Delay the execution of findOrCreateUser and execute 
        // the method in the next tick of the event loop
        process.nextTick(findOrCreateUser);
      }))
};

任何人都可以建议,我怎样才能使它工作?

标签: node.jsmongodbpassport.js

解决方案


Try creating the user by passing an object to the constructor instead of changing the properties individually.

newUser = new User({ username: username, email: emal, password: password });

推荐阅读