Node.js express4.x 登录验证中间件

/**
 * Created by yang on 2016/7/8.
 */
var loging =false;
var  re = require("http");
var  express= require("express");

var app ;
app= express();
basicAuth = require("basic-auth")
var auth = function(req, resp, next) {
    function unauthorized(resp) { 
        console.log("需要登录")
          resp.set('WWW-Authenticate', 'Basic realm=Input User&Password');
        return resp.sendStatus(401);
    }

    var user = basicAuth(req);

    if (!user || !user.name || !user.pass) {
        return unauthorized(resp);
    }

    if (user.name === 'admin' && user.pass === '123') {
        return next();
    } else {
        console.log("未能登录")
        return unauthorized(resp);
    }
};
//任何POST访问都经过此 检查登录状态 之前已登录调用next处理post参数 auth验证中间件
app.post('*', auth, function(req, resp,next) {
    console.log("登录成功")
    next()
});
//任何get访问都经过此 检查登录状态 之前已登录调用next处理get参数 auth验证中间件
app.get('*', auth, function(req, resp,next) {
    console.log("登录成功")
    next()
});
app.post('/test',function(req,res,next){
        console.log("post")
        req.on("data",function(data)
        {
           console.log(data.toString());
           res.send("ok")
        });

});

app.listen(1236,"0.0.0.0");

Node.js express4.x 登录验证中间件_第1张图片

使用post来登录

  function  nodejs_loging()
    {
        var  x = new XMLHttpRequest();

        x.onreadystatechange =function()
        {
            if(x.readyState == 4) {

                if(x.status == 200) {
                    console.log("The server replied with: " + x.responseText);
                    txt.text = x.responseText;


                }else{
                    console.log(x.status)
                }


            }
        };
        var xxx =new Object;
        var d="test.jpg"
        console.log(typeof d)
        x.open("POST","http://192.168.0.105:1236/test",true,"admin","123"); 
        x.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        x.send("数据");
    }

发送post请求,调用test,服务器接收请求并且检验登录状态,然后处理请求做响应操作,例子中简单返回ok字符串
这里写图片描述

你可能感兴趣的:(Node-js)