zoukankan      html  css  js  c++  java
  • 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"
        }
    }
  • 相关阅读:
    VMware安装Centos7过程记载
    php服务器设置指示
    php变化变量
    php参数
    php变量类型
    php外界PHP变量
    php语句的脱离方法
    PHP算术操作符
    PHP通过调用传递(Passingbyreference)
    php初始化数组
  • 原文地址:https://www.cnblogs.com/qianlegeqian/p/4221968.html
Copyright © 2011-2022 走看看