邮递员中意外的“”要求使用护照注册帐户,续集和表达

时间:2018-08-07 12:26:25

标签: node.js express sequelize.js passport.js

我的护照有问题,并在Node.js项目中进行了续集。实际上,当我想注册时,我正在使用邮递员来调用/ users / signup路由,它向我显示:Unexpected''和:

::1 - - [07/Aug/2018:09:20:19 +0000] "POST /users/signup HTTP/1.1" - - "-" "PostmanRuntime/7.2.0"
Executing (default): SELECT "user_id", "username", "name", "firstname", "email", "type", "location", "password", "createdAt", "updatedAt" FROM "users" AS "users" LIMIT 1;

有代码:

/* CREATE an account */
  app.post('/users/signup', (req, res) => {

      db.users.find({ $or: [{ email: req.body.email }, { username: req.body.username }] }).then(user => {

  if (err) {
    return res.send(err);
  }
  if (user) {
    if (user.email == req.body.email) {
      return res.send("This email is already taken.")
    }
    return res.send("This username is already taken.")
  }
  else {

    const data = {
      username: req.body.username,
      name: req.body.name,
      firstname: req.body.firstname,
      email: req.body.email,
      location: req.body.location,
      type: req.body.type,
      password: req.body.password
    };

    db.users.create({
      username: data.username,
      name: data.name,
      firstname: data.firstname,
      email: data.email,
      location: data.location,
      type: data.type,
      password: data.password

    }).then(newUser => {
      res.send("newUser saved to database")
      // `req.user` contains the authenticated user.
      //TODO : res.redirect('/profile/' + req.body.username);
    })
      .catch(err => {
        console.log(err);
        res.status(400).send("unable to save this newUser to database");
      })

  }

}).catch(err => {
  console.log(err);
  res.status(400).send("signup failed");
})
})

还有我的模型(db.users):

const bcrypt = require("bcrypt-nodejs");

module.exports = (sequelize, DataTypes) => {
  // TABLE USERS
  const Users = sequelize.define('users', {

      user_id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      username: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false
      },
      firstname: {
        type: DataTypes.STRING,
        allowNull: false
      },
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
          isEmail: true
        }
      },
      type: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      location: {
        type: DataTypes.STRING
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false
      }
  });

      // methods ======================
      // generating a hash
      Users.generateHash = function (password) {
        return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
      };

      // checking if password is valid
      Users.validPassword = function (password) {
        return bcrypt.compareSync(password, this.password);
      };

      //hashing a password before saving it to the database
      Users.beforeCreate('save', function (next) {
        var user = this;
        bcrypt.hash(user.password, 10, function (err, hash) {
          if (err) {
            return next(err);
          }
          user.password = hash;
          next();
        })
      });

      return Users;
    };
My passport.js :



 // load all the things we need
    var LocalStrategy = require('passport-local').Strategy;
    var db = require('../db')

    // expose this function to our app using module.exports
    module.exports = function (passport) {
    var User = db.users;
    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

// used to deserialize the user
passport.deserializeUser(function (id, done) {
    User.find({
        where: { user_id: user_id }
    })
        .then(function (user) {
            done(err, user);
        }).catch(function (err) {
            return done(err);
        })
});


    // =========================================================================
    // LOCAL LOGIN =============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-login', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true // allows us to pass back the entire request to the callback
    },
        function (req, email, password, done) { // callback with email and password from our form

            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            User.findOne({ email : email }, function (err, user) {
                // if there are any errors, return the error before anything else
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user)
                    return done(null, false, { message: 'User not found.' }); // req.flash is the way to set flashdata using connect-flash
                // if the user is found but the password is wrong
                if (!user.validPassword(password))
                    return done(null, false, { message: 'Incorrect password.' }); // create the loginMessage and save it to session as flashdata

                // all is well, return successful user
                return done(null, user);
            });

        }));

};

我找不到问题的根源。我是Node.js的新手,而且几个小时以来一直陷于困境。这里有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

类似这样的东西:

db.users.find({where:{id:1}})
.then(user=>{
  // some code
}).error(err=>{
  throw err;
})