Search code examples
node.jspixelhttpresponsegif

node.js set cookie and send gif in response


I wrote a script in node.js (base on web beacon pixel), that need to set cookie and send a pixel back to the client.

My problem is that the cookie is not setting , if i remove from the code the part that send the GIF its working, but i cant find a way to make this 2 thing together set a cookie and send the GIF back.

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);

Solution

  • http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers:

    “This method must only be called once on a message”

    Just add the Set-Cookie header in your res.WriteHead call that sets the Content-type:

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