nodejs 實現cookie

來源:互聯網
上載者:User

以下代碼是正在寫的initnode架構中的代碼,可能你在實現cookie的時候不能全部拷貝
cookie實現,主要是發送頭部訊息:
[javascript] 
res.setHeader("Set-Cookie", cookieArr);  
res.setHeader("Set-Cookie", ['username=xxx', 'age=xxx;path=/foo']); //注意:多個cookie需要一次發送,多次調用這個發送頭部函數只生效最後一次 
完整的HTTP SETCOOKIE頭:
Set-Cookie:customer=huangxp; path=/foo;domain=.ibm.com;
expires= Wednesday, 19-OCT-05 23:12:40 GMT; [secure]
所以要實現cookie設定,需要自己組裝上面的cookie頭資訊,詳細參照以下代碼:set_cookie函數
[javascript] 
/*
 *  initNode架構  Request 請求類
 *  核心函數
 */ 
var request = function () { 
 
    var _this       = this; 
    var req         = null; //request對象 
    var res         = null; 
    var postData    = null; //存放POST資料 
    var getData     = null; //存放GETDATA資料 
    var cookieData  = null; //存放cookie資料 
    var cookieArr   = []; //存放cookie輸出資料 
    var url         = require("url"); 
    var util        = require('util'); 
    var querystring = require('querystring'); 
    var os          = require('os'); 
 
     
    /*  
     *  說明:Request 請求初始化
     */ 
    this.init = function (initnode) { 
        req         = initnode.req; 
        res         = initnode.res; 
        postData    = this._post(initnode.postData); 
        getData     = this._get(req); 
        cookieData  = this._cookie(req); 
    }; 
 
    /*  
     *  說明:GET方法,擷取URL中的GET提交資料
     *  使用:
     *  擷取單個    initnode.request.get('username');
     *  擷取多個    initnode.request.get(['username', 'age']);
     *  擷取全部    initnode.request.get('');
     */ 
    this.get = function (name) { 
        return this._requestData(name, getData); 
    }; 
 
     
    /*  
     *  說明:POST方法,擷取URL中的POST提交資料
     *  使用:
     *  擷取單個    initnode.request.post('username');
     *  擷取多個    initnode.request.post(['username', 'age']);
     *  擷取全部    initnode.request.post('');
     */ 
    this.post = function (name) { 
        return this._requestData(name, postData); 
    }; 
 
    /*  
     *  說明:COOKIE方法,擷取URL中的COOKIE提交資料
     *  使用:
     *  擷取單個    initnode.request.get_cookie('username');
     *  擷取多個    initnode.request.get_cookie(['username', 'age']);
     *  擷取全部    initnode.request.get_cookie('');
     */ 
    this.get_cookie = function (name) { 
        return this._requestData(name, cookieData); 
    }; 
     
    /*  
     *  說明:設定COOKIE
     *  使用:
     *  設定Cookie initnode.request.set_cookie('username', 'initnode', 30, '/');
     *  name    cookie名稱
     *  value   cookie值
     *  expires 有效期間時間,秒計算
     *  path    有效目錄
     *  domain  網域名稱
     */ 
    this.set_cookie = function (name, value, expires, path, domain) { 
        var cookieSrt = ''; 
        cookieStr = name + '=' + value + ';'; 
        //cookie有效期間時間 
        if (expires != undefined) { 
            expires = parseInt(expires); 
            var today = new Date(); 
            var time = today.getTime() + expires * 1000; 
            var new_date = new Date(time); 
            var expiresDate = new_date.toGMTString(); //轉換成GMT 格式。 
            cookieStr += 'expires=' +  expiresDate + ';'; 
        } 
        //目錄 
        if (path != undefined) { 
            cookieStr += 'path=' +  path + ';';  
        } 
        //網域名稱 
        if (domain != undefined) { 
            cookieStr += 'domain=' +  domain + ';';  
        } 
        cookieArr.push(cookieStr); 
        return true; 
    } 
     
    /*  
     *  說明:設定COOKIE
     *  使用:
     *  設定Cookie initnode.request.set_cookie('username', 'initnode', 30, '/');
     *  name    cookie名稱
     *  value   cookie值
     *  expires 有效期間時間,秒計算
     *  path    有效目錄
     *  domain  網域名稱
     */ 
    this.del_cookie = function (name) { 
        this.set_cookie(name, '', -999); 
        return true; 
    } 
     
    /*  
     *  說明:header頭部發送cookie設定資訊
     *  使用:
     *  設定Cookie initnode.request.flush_cookie();
     */ 
    this.flush_cookie = function () { 
        res.setHeader("Set-Cookie", cookieArr);  
    } 
 
    /*  
     *  說明:擷取HTTP頭部資料資訊
     *  使用:
     *  擷取單個    initnode.request.headers('accept');
     *  擷取多個    initnode.request.headers(['referer', 'referer']);
     *  擷取全部    initnode.request.headers('');
     *  參數:accept referer accept-language user-agent content-type 
     *  accept-encoding host content-length connection cache-control cookie 
     */ 
    this.headers = function (name) { 
        return this._requestData(name, req.headers); 
    }; 
     
    /*  
     *  說明:擷取用戶端IP地址
     *  使用:
     *  initnode.request.getClientIp();
     */ 
    this.getClientIp = function () { 
        var ipAddress; 
        var forwardedIpsStr = this.headers('x-forwarded-for');  
        if (forwardedIpsStr) { 
            var forwardedIps = forwardedIpsStr.split(','); 
            ipAddress = forwardedIps[0]; 
        } 
        if (!ipAddress) { 
            ipAddress = req.connection.remoteAddress; 
        } 
        return ipAddress; 
    }; 
     
    /*  
     *  說明:擷取用戶端IP地址
     *  使用:
     *  initnode.request.getServer('hostname');
     *  hostname 主機名稱
     *  type 作業系統類型
     *  release 髮型版本
     *  uptime  更新時間
     *  loadavg 平均負載
     *  totalmem 總記憶體
     *  freemem 空閑記憶體
     *  cpus CUP
     */ 
    this.getServer = function (name) { 
        if (os[name]) { 
            return os[name](); 
        } else { 
            return '';   
        } 
    } 
 
    /*  
     *  從req頭部資訊中擷取cookie,並且轉化成對象格式
     */ 
    this._cookie = function (req) { 
        return querystring.parse(req.headers.cookie); 
    }; 
 
    /*  
     *  擷取POSTDATA資料
     */ 
    this._post = function (_postData) { 
        return querystring.parse(_postData); 
    }; 
 
    /*   
     *  擷取GET資料
     */ 
    this._get = function (req) { 
        var getQuery= url.parse(req.url).query; 
        var getData = querystring.parse(getQuery); //getData資料 
        return getData; 
    }; 
 
    //封裝GET,POST擷取資料介面 
    this._requestData = function (name, data) { 
        if (name == '') { 
            return data; 
        } 
        if (typeof(name) == 'object') { //數組形式傳遞進來 
            var temp = {}; 
            for (var i = 0; i < name.length; i++) { 
                if (data[name[i]]) { 
                    temp[name[i]] = data[name[i]]; 
                } else { 
                    temp[name[i]] = ''; 
                } 
            } 
            return temp; 
        } else { 
            if (data[name]) { 
                return data[name]; 
            } else { 
                return ''; 
            } 
        } 
    }; 
 

 
module.exports = request; 
 
使用方法:
[javascript] 
initnode.request.set_cookie('username', 'zhuli'); 
initnode.request.set_cookie('age131', 100, 3000, '/'); 
initnode.request.del_cookie('age11'); 
initnode.request.del_cookie('age12'); 
initnode.request.del_cookie('age13'); 
initnode.request.del_cookie('age141'); 
initnode.request.del_cookie('age131'); 
initnode.request.flush_cookie(); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.