你能帮我创建 cookie,因为我无法让它工作。我想在用户登录后设置和创建 cookie,但我不知道我的代码有什么问题。多谢你们。
这是我的代码,如果您认为还有其他错误或代码更正,您可以帮我修复它吗?多谢你们。:)
应用程序.js
//deps
var express = require('express');
var app = express();
var redis = require('redis');
var client = redis.createClient();
var delcookie = function(req, res) { res.clearCookie('login_token'); res.redirect('/'); };
var setcookie = function(req, res) { res.cookie('login_token', +new Date(), { maxAge: 3600000, path: '/' }); res.redirect('/'); };
//configs
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(app.router);
client.on('error', function (err) {
console.log('Error: ' + client.host + ':' + client.port + ' - ' + err);
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/login/', function (req, res) {
res.sendfile(__dirname + '/login.html');
});
app.get('/register/', function (req, res) {
res.sendfile(__dirname + '/register.html');
});
app.get('/restricted/', function (req, res) {
res.sendfile(__dirname + '/restricted.html');
});
app.get('/logout/', delcookie, function (req, res) {
res.sendfile(__dirname + '/logout.html');
});
//post
app.post('/login/', function (req, res) {
//res.sendfile(__dirname + '/restricted.html');
client.hmget( req.body.user.username, 'password', function (err,pass) {
if ( (!err) && pass && pass == req.body.user.password ){
res.redirect('/restricted/', setcookie);
} else if ( pass == false) {
res.redirect('/register/');
} else {
res.redirect('/login/');
}
});
});
app.post('/register/', function (req, res) {
client.hmset(req.body.user.username, 'password',req.body.user.password,
'fname',req.body.user.fname, 'lname', req.body.user.lname,
'password', req.body.user.password, 'email', req.body.user.email,
'mobile', req.body.user.mobile, redis.print);
res.write('Successfully Registered');
});
app.listen(80);