通过Nodejs设置cookie方法:

  • 新建cookie.js,代码如下:

    var http = require('http');
    http.createServer(function (req, res) {
        // 获得客户端的Cookie
        var Cookies = {};
        req.headers.cookie && req.headers.cookie.split(';').forEach(function( Cookie ) {
            var parts = Cookie.split('=');
            Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
        });
        console.log(Cookies);
        // 向客户端设置一个Cookie
        res.writeHead(200, {
            'Set-Cookie': ['username=huangh','password=123456'],
            'Content-Type': 'text/plain'
        });
        res.end('Hello World\n');
    
    }).listen(8000);
    
    console.log('Server running at http://127.0.0.1:8000/');
    
    
  • 终端执行 :node cookie.js

  • 浏览器中输入:http://127.0.0.1:8000/

    效果图

  • 终端结果如下:

    效果图

以上文章来自:黄卉 , https://huanghui8030.github.io/node/cookie.html