【发布时间】:2015-03-20 08:13:27
【问题描述】:
我正在学习 MEAN machine 节点身份验证教程。
这是他们的源代码:https://github.com/scotch-io/mean-machine-code/blob/master/10-node-authentication/server.js 除了apiRouter.post('/authenticate', 部分,我基本上什么都有了
Express API 正在运行:
http://localhost:8615/api/users 将返回来自 scotch.io 的 MongoDB 的用户列表
以下是 /api/users 的 API:
apiRouter.route('/users')
// create a user (accessed at POST http://localhost:8615/api/users)
.post(function(req, res) {
// create a new instance of the User model
var user = new User();
// set the users information (comes from the request)
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
// save the user and check for errors
user.save(function(err) {
if (err) {
// duplicate entry
if (err.code == 11000)
return res.json({ success: false, message: 'A user with that username already exists. '});
else
return res.send(err);
}
// return a message
res.json({ message: 'User created!' });
});
})
// get all users (access at GET http://localhost:8615/api/users)
.get(function(req, res) {
User.find(function(err, users) {
if (err) return res.send(err);
// return the users
res.json(users);
})
});
这是我的 user.js 用户架构
// SCHEMAS ------------------------------------
// user schema
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false }
// ^ select false will not return passwords
});
// hash the password before the user is saved
UserSchema.pre('save', function(next) {
var user = this;
// PUT username
if (!user.isModified('username')) return next();
// PUT name
if (!user.isModified('name')) return next();
// hash the password only if the password has been changed or user is new
if (!user.isModifited('password')) return next();
// generate the salt
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);
// change the password to the hashed version
user.password = hash;
next();
});
});
从书中:
创建示例用户
首先,我们需要确保我们甚至有一个用户进行身份验证 因为在上一章结束时,我们删除了所有人。让我们 使用 POST http://localhost:8080/api/users 路由创建用户 我们在 API 中创建了将用户添加到我们的数据库。
我们将发送一个包含以下信息的 POST 请求:姓名 Chris 用户名 chris 密码 supersecret
我正在使用 Postman 添加新用户,如您所见,我已经为用户名和密码输入了键/值对,但是收到错误消息“验证失败”“需要用户名”“需要密码” :
更新,我刚刚尝试了 x-www-form-urlencoded 并得到以下错误
GET /api/users 200 66.141 ms - 655
••• API CRUD hit •••
/Users/leongaban/NodeDallas/projects/awesome-test/app/models/user.js:27
if (!user.isModifited('password')) return next();
^
TypeError: Object { password: 'supersecret',
username: 'Chris',
name: 'chris',
_id: 54c001dc4ee4028c18e61334 } has no method 'isModifited'
at model.UserSchema.methods.comparePassword.user (/Users/leongaban/NodeDallas/projects/awesome-test/app/models/user.js:27:12)
Postman 中的错误截图:https://s3.amazonaws.com/f.cl.ly/items/1M0M392M0E3b2i430I1n/Image%202015-01-21%20at%201.45.51%20PM.png
【问题讨论】:
标签: node.js mongodb api authentication express