首页 > 代码库 > nodejs 学习(2) 中间件

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="http://www.mamicode.com/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"    }}

 

nodejs 学习(2) 中间件