我希望能够设置一个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中获取上述代码,然后在其中工作一个cookie。
无法快速访问获取/设置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/');
这会将所有cookie存储到cookie对象中,并且在编写头部时需要设置cookie。