Set-Cookie: cookieName=cookieValue;
[expires=]
[;domain=]
[;path=]
[;secure=]
[;httpOnly=]
var http = require('http');
http.createServer(function (req, res) {
// 获得客户端的Cookie var Cookies = {};
req.headers.cookie && req.headers.cookie.split(';').forEach(function( Cookie ) { // forEach编辑数组 var parts = Cookie.split('='); // 以=为分隔符,把字符串分隔成数组 Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim(); // 把数组内容以json的形式存储 });
console.log(Cookies) // 打印cookie // 向客户端设置一个Cookie res.writeHead(200, {
'Set-Cookie': 'myCookie=test', // cookie名=cookie值 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
访问:http://localhost:8000/ 然后F12打开开发者工具(以chrome浏览器为例)
当然在控制页面中也可以看到
res.writeHead(200, {
'Set-Cookie': ["aaa=bbb","ccc=ddd","eee=fff"], // 以数组的形式设置 'Content-Type': 'text/plain' });
浏览器返回结果:
控制面板返回结果:
var http = require('http');
http.createServer(function (req, res) {
// 获得客户端的Cookie var Cookies = {};
req.headers.cookie && req.headers.cookie.split(';').forEach(function( Cookie ) {
var parts = Cookie.split('=');
Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
});
console.log(Cookies)
// 向客户端设置一个Cookie res.writeHead(200, {
'Set-Cookie': 'name=zhangsan; Expires=Wed, 13-Jan-2021 22:23:01 GMT; HttpOnly ',
'Content-Type': 'text/html' });
res.end('Hello World\n'); }
).listen(8000); console.log('Server running at http://127.0.0.1:8000/');
浏览器返回结果:
、
HttpOnly 属性 : 这是微软对Cookie做的扩展。如果在Cookie中设置了"HttpOnly"属性,那么通过程序(JS脚本、Applet等)将无法读取到Cookie信息,这样能有效的防止XSS攻击。)
把值设为空字符串,把有效期值0
res.writeHead(200, { 'Set-Cookie': 'name=""; Expires=0', 'Content-Type': 'text/html' });
相关优秀博文:
http://www.tuicool.com/articles/ya2eimE
http://www.tuicool.com/articles/F3UF7n
谢谢关注!