返回列表

Nodejs 操作cookie

默认分类 2014/04/22 04:19

参考资料:http://www.cnblogs.com/rubylouvre/archive/2012/08/19/2645644.html

var http = require('http');

function parseCookies (request) {
    var list = {},
    rc = request.headers.cookie;

    rc && rc.split(';').forEach(function( cookie ) {
    var parts = cookie.split('=');
        list[parts.shift().trim()] = unescape(parts.join('='));
    });

    return list;
}


http.createServer(function (request, response) {
    // To Read a Cookie
    var cookies = parseCookies(request);
    console.log(cookies);
    // To Write a Cookie
    response.writeHead(200, {
        'Set-Cookie': 'mycookie=test',
        'Content-Type': 'text/plain'
    });
    response.end('Hello World

' + JSON.stringify(cookies)); }).listen(8124);

console.log('Server running at 127.0.0.1:8124 ');