node.js设置cookie并发送gif作为回应

我在node.js(基于web beacon像素)中编写了一个脚本,需要设置cookie并将像素发送回客户端。

我的问题是,cookie是不是设置,如果我从代码中删除的部分,发送GIF的工作,但我无法find一种方法,使这两件事情在一起设置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

“这个方法只能在消息中调用一次”

只需在您的res.WriteHead调用中添加Set-Cookie标头来设置Content-type:

  res.writeHead(200, { 'Content-Type': 'image/gif', 'Set-Cookie' : '…' }); 
Interesting Posts