如何在mongodb中使用bcrypt哈希密码而没有注册页面?

问题描述

我有问题。我想用bcrypt直接在mongodb中注册一个用户(没有用于客户端的UI,我想直接通过查询管理它),然后从客户端使用REST API登录。有可能吗?

谢谢!

解决方法

可以肯定地,您可以运行Node API,然后向您使用 Postman 定义的端点发送POST请求,例如:

// Routes file. Import this file later in your app.js or index.js file
const express = require('express');
const router = express.Router(); 
/*   ..... also import any user model,file,etc....*/


router.post('/signup',(req,res,next)=>{
     const username = req.body.username;
     const password = req.body.password;

     bcrypt
        .hash(password,12) 
        .then(hashedPassword => {
            /* Your MongoDB logic. Example below */

            const user = new User({ // Example if you had a User Model
            email: email,password: hashedPassword
          });
          return user.save();
        })
        .then(result => {
        // To be more RESTful this should send the whole user in JSON              format after creation**
            res.status(201).json({ message: 'User created!'}); 
        })
      })
    .catch(err => {
    // Error logic. This is just an example
        if (!err.statusCode) {
            err.statusCode = 500;
        }
        next(err);
    });
});

module.exports = router;

为了更清楚一点,您也应该有一个controllers文件。如果您还希望登录,那么逻辑将很相似,创建一个端点,然后通过Postman或其他一些应用程序发送请求。