connect路由匹配问题
发布于 5天前 作者 SevenSharp 78 次浏览 来自 问答

var http = require(‘http’); var logger = require(‘morgan’);//日志 var bodyparser = require(‘body-parser’); var cookie = require(‘cookie-parser’); var session = require(‘express-session’); var connect = require(‘connect’); var user = require(‘./user’); var app = connect(); app.use(logger(‘dev’)); app.use(logger(‘:url’)); app.use(bodyparser.urlencoded({ extended: false })); app.use(cookie()); app.use(session({ secret: 'my app secret’, resave: false, saveUninitialized: true }));

//退出要放在前面why? app.use('/logout’, function (req, res, next) { if (req.method = “GET”) { req.session.logged_in = false; res.writeHead(200, { 'Content-Type’: ‘text/html’ }); res.end(‘Logged out’); } else {

    next();
}

}); app.use('/’, function (req, res, next) { if (‘GET’ == req.method&&req.session.logged_in) { res.writeHead(200, { 'Content-Type’: ‘text/html’ }); res.end(' Welcome to back ' + req.session.name + ''+ 'Logout' );
} else { next();

}

}); app.use('/’, function (req, res, next) { if (‘GET’ == req.method) { res.writeHead(200, { 'Content-Type’: ‘text/html’ }); res.end([ '<form action="/login" method="POST">' , '<input name="user" type="text" />
' , '<input type="text" name="pwd">
' , '<button>Submit</button>' , '</form>' ].join(' ')); } else { next(); } }); app.use('/login’, function (req, res, next) { if (‘POST’ == req.method) { res.writeHead(200, { 'Content-Type’: ‘text/html’ }); if (!user[req.body.user] || req.body.pwd != user[req.body.user].password) { res.end(“Bad username/password”); } else { req.session.logged_in = true; req.session.name = user[req.body.user].name; res.end(‘Authenticated’); } } else { next(); } }); http.createServer(app).listen(3000);

1 回复

处理退出的代码放在最后执行就有问题。 app.use('/logout’, function (req, res, next) { if (req.method = “GET”) { req.session.logged_in = false; res.writeHead(200, { 'Content-Type’: ‘text/html’ }); res.end(‘Logged out’); } else {

next();

}

回到顶部