我在node.js中编写了一个脚本(基于网络信标像素),需要设置cookie并将像素发送回客户端。
我的问题是 cookie 没有设置,如果我从代码中删除发送 GIF 的部分,但我找不到一种方法让这两个东西一起设置 cookie 并将 GIF 发送回来。
http = require('http');
url = require('url');
http.createServer(function(req, res){
var requestURL = url.parse(req.url, true);
if (requestURL.pathname == '/log.gif') {
// Write a Cookie
res.writeHead(200, {
'Set-Cookie' : 'id='+requestURL.query.id+'; expires=' + new Date(new Date().getTime()+86409000).toUTCString()
});
var imgHex = '47494638396101000100800000dbdfef00000021f90401000000002c00000000010001000002024401003b';
var imgBinary = new Buffer(imgHex, 'hex');
res.writeHead(200, {'Content-Type': 'image/gif' });
res.end(imgBinary, 'binary');
} else {
res.writeHead(200, {'Content-Type': 'text/plain' });
res.end('');
}
}).listen(8080);
最佳答案
http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers :
“This method must only be called once on a message”
只需在设置 Content-type 的 res.WriteHead
调用中添加 Set-Cookie header 即可:
res.writeHead(200, {
'Content-Type': 'image/gif',
'Set-Cookie' : '…'
});
关于node.js 设置 cookie 并发送 gif 作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15521951/