简体   繁体   English

不了解Node.js中的Cookie

[英]Not understanding Cookies in Node.js

I am making a program in Node.js that involves cookies. 我正在Node.js中制作一个涉及cookie的程序。 I don't want to use a library like express. 我不想使用像快递这样的库。 I found the following code online for using cookies, but I am not exactly sure how it works. 我在网上找到了以下使用cookie的代码,但我不确定它是如何工作的。 Could somebody break it down for me? 有人可以为我分解吗? Also, I am not sure which part of the code reads cookies in the system and which part writes them. 另外,我不确定代码的哪一部分读取系统中的cookie以及哪些部分写入它们。 Could you clarify that as well? 你能澄清一下吗?

Thank you: 谢谢:

Here is the code: 这是代码:

var http = require('http');

function parseCookies(cookie) {
    return cookie.split(';').reduce(
        function(prev, curr) {
            var m = / *([^=]+)=(.*)/.exec(curr);
            var key = m[1];
            var value = decodeURIComponent(m[2]);
            prev[key] = value;
            return prev;
        },
        { }
    );
}

function stringifyCookies(cookies) {
    var list = [ ];
    for (var key in cookies) {
        list.push(key + '=' + encodeURIComponent(cookies[key]));
    }
    return list.join('; ');
}

http.createServer(function (request, response) {
  var cookies = parseCookies(request.headers.cookie);
  console.log('Input cookies: ', cookies);
  cookies.search = 'google';
  if (cookies.counter)
    cookies.counter++;
  else
    cookies.counter = 1;
  console.log('Output cookies: ', cookies);
  response.writeHead(200, {
    'Set-Cookie': stringifyCookies(cookies),
    'Content-Type': 'text/plain'
  });
  response.end('Hello World\n');
}).listen(1234);

Cookies are just a piece of text that's sent as a header when the browser sends a request to a server. Cookie只是在浏览器向服务器发送请求时作为标题发送的一段文本。 The server can then modify the cookies if it wants, and send them back as a header to the browser. 然后,服务器可以根据需要修改cookie,并将其作为标题发送回浏览器。

The convention for cookies is that they are key-value pairs separated by an ampersand ( & ), just like a query string in a URL (which is why decodeURIComponent and encodeURIComponent work in your example!). Cookie的约定是它们是由和号( & )分隔的键值对,就像URL中的查询字符串一样(这就是为什么decodeURIComponentencodeURIComponent在你的例子中工作!)。

parseCookies reads from the cookie string to an object representing your cookies. parseCookies从cookie字符串读取代表cookie的对象。 Eg. 例如。

// Input
"foo=bar&baz=42"

// Output
{foo: "bar", baz: 42}

stringifyCookies takes that cookie object, and converts it back to a cookie: stringifyCookies获取该cookie对象,并将其转换回cookie:

// Input
{foo: "bar", baz: 42}

// Output
"foo=bar&baz=42"

Does that make sense? 那有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM