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

标签 node.js pixel httpresponse gif

我在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/

相关文章:

node.js - Express-jwt 中间件 typescript 类型问题

Python/PyGame : Find pixel by colorcode

c# - 从像素坐标列表中查找圆的中心坐标 C#

javascript - 是否可以在 Node js 中操作 DOM?

node.js - 在 typescript 中使用 d.ts 扩展外部模块

python - 使用 matplotlib 制作 2D 像素图

c# - Web API、IQueryable、OData 和 HttpResponseMessage 作为返回类型?

python - 如何让lambda函数返回包含python中图像的json

android - 使用 retrofit 2 下载 POST 方法的 PDF 响应

javascript - 使用 MongoDB、Express、Node.Js 和 GridFS-stream 存储视频和图片文件