使用Node.js HTTP服务器获取并设置一个Cookie

我希望能够设置一个cookie,并读取每个对nodejs服务器实例的请求的单个cookie。 可以在几行代码中完成,而不需要拉入第三方库?

var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World\n'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/'); 

试图直接从nodejs.org获取上面的代码,并将cookiejoin其中。

没有快速的function获取/设置cookie,所以我想出了以下黑客:

 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\n'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/'); 

这将把所有的cookies存储到cookie对象中,并且当你写头时你需要设置cookie。

如果您使用快速库,就像许多node.js开发者所做的那样,有一种更简单的方法。 检查Express.js文档页面以获取更多信息。

上面的parsing示例工作,但expression给你一个很好的function来处理:

 app.use(express.cookieParser()); 

设置一个cookie:

 res.cookie('cookiename', 'cookievalue', { maxAge: 900000, httpOnly: true }); 

要清除cookie:

 res.clearCookie('cookiename'); 

RevNoah对使用Express的cookieparsing器的build议有最好的答案。 但是,这个答案现在已经3岁了,已经过时了。

使用Express ,您可以按如下所示读取cookie

 var express = require('express'); var cookieParser = require('cookie-parser'); var app = express(); app.use(cookieParser()); app.get('/myapi', function(req, resp) { console.log(req.cookies['Your-Cookie-Name-Here']; } 

用下面的代码更新你的package.json ,replace适当的最新版本。

 "dependencies": { "express": "4.12.3", "cookie-parser": "1.4.0" }, 

这里描述了更多的操作,比如设置和parsingcookie

您可以使用“cookies”npm模块,该模块具有全面的function。

文档和示例:
https://github.com/jed/cookies

Cookies 通过HTTP头传输
你只需要parsing请求头并放置响应头。

要获取Cookie分解程序以使用Cookie值中包含“=”的Cookie:

 var get_cookies = function(request) { var cookies = {}; request.headers && request.headers.cookie.split(';').forEach(function(cookie) { var parts = cookie.match(/(.*?)=(.*)$/) cookies[ parts[1].trim() ] = (parts[2] || '').trim(); }); return cookies; }; 

然后得到一个单独的cookie:

 get_cookies(request)['my_cookie'] 

作为@Corey Hart的回答,我改写了parseCookies()

  • String.prototype.split – 将cookiestring转换为列表
  • Array.prototype.reduce – 将列表转换为单个对象
  • RegExp.prototype.exec – 使用正则expression式来parsing“名称=值”string

这是一个工作的例子:

 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); 

我也注意到OP使用http模块。 如果OP在使用restify ,他可以使用restify-cookies :

 var CookieParser = require('restify-cookies'); var Restify = require('restify'); var server = Restify.createServer(); server.use(CookieParser.parse); server.get('/', function(req, res, next){ var cookies = req.cookies; // Gets read-only cookies from the request res.setCookie('my-new-cookie', 'Hi There'); // Adds a new cookie to the response res.send(JSON.stringify(cookies)); }); server.listen(8080); 

这是一个用于pipe理节点中cookie的整齐的复制粘贴补丁。 我会用CoffeeScript来做这个美女

 http = require 'http' http.IncomingMessage::getCookie = (name) -> cookies = {} this.headers.cookie && this.headers.cookie.split(';').forEach (cookie) -> parts = cookie.split '=' cookies[parts[0].trim()] = (parts[1] || '').trim() return return cookies[name] || null http.IncomingMessage::getCookies = -> cookies = {} this.headers.cookie && this.headers.cookie.split(';').forEach (cookie) -> parts = cookie.split '=' cookies[parts[0].trim()] = (parts[1] || '').trim() return return cookies http.OutgoingMessage::setCookie = (name, value, exdays, domain, path) -> cookies = this.getHeader 'Set-Cookie' if typeof cookies isnt 'object' cookies = [] exdate = new Date() exdate.setDate(exdate.getDate() + exdays); cookieText = name+'='+value+';expires='+exdate.toUTCString()+';' if domain cookieText += 'domain='+domain+';' if path cookieText += 'path='+path+';' cookies.push cookieText this.setHeader 'Set-Cookie', cookies return 

现在您可以像预期的那样处理cookies了:

 server = http.createServer (request, response) -> #get individually cookieValue = request.getCookie 'testCookie' console.log 'testCookie\'s value is '+cookieValue #get altogether allCookies = request.getCookies() console.log allCookies #set response.setCookie 'newCookie', 'cookieValue', 30 response.end 'I luvs da cookies'; return server.listen 8080 

第一个需要创buildcookie(我已经包装cookie中的标记为例),然后将其设置为响应。要以下列方式使用cookie安装cookieParser

 app.use(cookieParser()); 

浏览器会将其保存在“资源”选项卡中,然后将其用于以初始URL为基础的每个请求

 var token = student.generateToken('authentication'); res.cookie('token', token, { expires: new Date(Date.now() + 9999999), httpOnly: false }).status(200).send(); 

从服务器端的请求获取cookie也很容易。您必须通过调用请求对象的“cookie”属性来从请求中提取cookie。

 var token = req.cookies.token; // Retrieving Token stored in cookies 

为了得到一个单一的cookie,这个代码将比parsing所有的cookies更快:

 getSingleCookie = (cookie, name) -> vIx = cookie.indexOf "#{name}=" if vIx != -1 egalIx = vIx+name.length+1 colIx = cookie.indexOf ';', egalIx v = if colIx == -1 cookie.substring egalIx else cookie.substring egalIx, colIx return v 

应该使用像:

 getSingleCookie request.headers, 'my_cookie'