使用Node.js HTTP服务器获取和设置单个Cookie [英] Get and Set a Single Cookie with Node.js HTTP Server
本文介绍了使用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\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
只是想直接从nodejs.org接受上面的代码, / p>
Just trying to take the above code directly from nodejs.org, and work a cookie into it.
推荐答案
没有快速访问获取/设置Cookie的功能,所以我想出了以下黑客:
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\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
这会将所有Cookie存储到Cookie对象中,并且当您写头时需要设置Cookie 。
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屋!
查看全文