我想用mongoDB使用Mongoose來測試REST API的身份驗證(它可以正常編碼ref用戶),但我不確定我是在用我的登錄函數在我的身份驗證控制器ES6 REST API與Mongoose無法正確登錄
user.model.js
M端口...
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
pwd: {
type: String,
required: true
}
});
UserSchema.method({
});
UserSchema.statics = {
/**
* Get user
* @param {ObjectId} id - The objectId of user.
* @returns {Promise<User, APIError>}
*/
get(id) {
return this.findById(id)
.exec()
.then((user) => {
if (user) {
return user;
}
const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
return Promise.reject(err);
});
},
/**
* List users in descending order of 'createdAt' timestamp.
* @param {number} skip - Number of users to be skipped.
* @param {number} limit - Limit number of users to be returned.
* @returns {Promise<User[]>}
*/
list({ skip = 0, limit = 50 } = {}) {
return this.find()
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit)
.exec();
}
};
export default mongoose.model('User', UserSchema);
那麼我
個auth.controller.js
import ...
import User from '../../models/user.model';
function login(req, res, next) {
User.findOne({ username: req.body.username, password: req.body.password }, (err, user) => {
if (err) {
return next(new APIError('Authentication error', httpStatus.UNAUTHORIZED, true));
}
const token = jwt.sign({ username: user.username }, config.jwtSecret);
return res.json({ token, username: user.username });
});
}
,我正與
auth.test.js
import ...
describe('## Auth APIs',() => {
const validUserCredentials = {
username: 'testUser',
password: 'testUserPwd'
};
let jwtToken;
describe('# POST /api/v1/auth/login',() => {
it('should get valid JWT token', (done) => {
request(app)
.post('/api/v1/auth/login')
.send(validUserCredentials)
.expect(httpStatus.OK)
.then((res) => {
expect(res.body).to.have.property('token');
jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => {
expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions
expect(decoded.username).to.equal(validUserCredentials.username);
jwtToken = `Bearer ${res.body.token}`;
done();
});
})
.catch(done);
});
});
});
但我的認證測試失敗,因爲我得到任何數據測試來自DB
Uncaught TypeError:無法讀取屬性'用戶名'null
我在哪裏錯了?感謝您的反饋
有三個'username'特性,這種特性引起它:'req.body.username','user.username'或'decoded.username'。哪一個導致錯誤? – robertklep
感謝您的反饋...我發現這個問題,它與Promise用法相關聯 我的登錄函數寫錯了... – erwin