使用 Node.js HTTP 服务器获取和设置单个 Cookie [英] Get and Set a Single Cookie with Node.js HTTP Server

查看:35
本文介绍了使用 Node.js HTTP 服务器获取和设置单个 Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够设置单个 cookie,并在每次向 nodejs 服务器实例发出请求时读取该单个 cookie.几行代码就能搞定,不需要拉第三方库?

I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World
');
}).listen(8124);

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

只是尝试直接从 nodejs.org 获取上述代码,然后将 cookie 放入其中.

Just trying to take the above code directly from nodejs.org, and work a cookie into it.

推荐答案

没有获取/设置 cookie 的快速功能访问,所以我想出了以下 hack:

There is no quick function access to getting/setting cookies, so I came up with the following hack:

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()] = decodeURI(parts.join('='));
    });

    return list;
}


http.createServer(function (request, response) {

  // To Read a Cookie
  var cookies = parseCookies(request);

  // To Write a Cookie
  response.writeHead(200, {
    'Set-Cookie': 'mycookie=test',
    'Content-Type': 'text/plain'
  });
  response.end('Hello World
');
}).listen(8124);

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

这会将所有的cookies存储到cookies对象中,写head时需要设置cookies.

This will store all cookies into the cookies object, and you need to set cookies when you write the head.

这篇关于使用 Node.js HTTP 服务器获取和设置单个 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆