nodejs 学习(2) 中间件

var connect=require(‘connect‘),
    morgan=require(‘morgan‘),//日志
    bodyparser=require(‘body-parser‘),
    session=require(‘cookie-sessions‘),
    users=require(‘./users‘),//测试数据
    server=connect();

    server.use(morgan(":method :url :res[content-type] :response-time"));//记录请求方法、URL、响应头与响应时间
    server.use(bodyparser.urlencoded({ extended: false }));
    server.use(bodyparser.json());
    server.use(session({secret: ‘my app secret‘}));


    server.use(function(req,res,next){//如果已登录
        if(‘/‘==req.url && session.logged_in){
            res.writeHead(200,{"Content-Type":"text/html"});
            res.end("Welcome back,<b>"+session["username"]+‘</b>.‘+‘<a href="/logout">logout</a>‘);
        }else{
            next();
        }
    });

    server.use(function(req,res,next){//未登录时显示表单
        if("/"==req.url && req.method=="GET"){
            res.writeHead(200,{"Content-Type":"text/html"});
            res.end([
                ‘<form action="/login" method="post">‘,
                ‘<fieldset>‘,
                ‘<legend>Please log in</legend>‘,
                ‘<p>User:<input type="text" name="user"></p>‘,
                ‘<p>Password:<input type="Password" name="password"></p>‘,
                ‘<button>Submit</button>‘,
                ‘</fieldset>‘,
                ‘</form>‘
            ].join(‘‘));
        }else{
            next();
        }
    });


    server.use(function(req,res,next){//登录成功
        if("/login"==req.url && "POST"==req.method){
            res.writeHead(200);
            if(!users[req.body.user] || users[req.body.user].password!==req.body.password){
                res.end(‘Bad username/password‘);
            }else{
                session.logged_in=true;
                session.username=users[req.body.user]["name"];
                res.end("Authenticated");
            }
        }else{
            next();
        }
    });

    server.use(function(req,res,next){//登出
        if("/logout"==req.url){
            session.logged_in=false;
            res.writeHead(200);
            res.end(‘Logged out‘);
        }else{
            next();
        }
    })




    server.listen(3000);

 //users.json

{
    "tobi":{
        "password":"ferret",
        "name":"Tobi Holowaychuk"
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。