这对我的网站来说真的是一个简单的登录解决方案。我使用angular2作为前端,将用户和密码作为JSON传递给表达服务器,使用mongoose在我的MongoDB中找到用户,然后在验证用户名和密码正确后给我一个令牌。
看看我的设置。
app.js我需要中间件
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var config = require('./config');
var index = require('./routes/index');
var productsRouter = require('./routes/productsRoute')();
var cartRouter = require('./routes/cartRoute')();
var userRouter = require('./routes/usersRoute')();
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('superSecret', config.secret);
我的config.js
module.exports = {
'secret': 'wingsareallineed',
}
和我的usersRoute.js
userRouter.route('/login')
.post(function(req, res){
console.log(user);
mongoose.connect(url, function(err){
users.findOne({username: req.body.username}, function(err, user){
if(err) throw err;
if(!user){
res.json({success: false, message: 'Authentication failed. User not found.'});
} else if(user) {
if(user.password != req.body.password){
res.json({success: false, message: 'Authentican failed. Wrong password.'});
} else {
var token = jwt.sign(user, app.get('superSecret'), {
expiresInMinutes: 1440
});
}
res.json({
success: true,
message: 'Success!',
token: token
});
}
mongoose.disconnect();
});
});
});
当我按下登录按钮时,我收到内部服务器错误。我错过了什么?