代码之家  ›  专栏  ›  技术社区  ›  Rahul Nanwani

响应未结束,浏览器继续加载-nodejs和graphicsmagick

  •  0
  • Rahul Nanwani  · 技术社区  · 10 年前

    我是nodejs的新手。在将图像发送到浏览器之前,我使用graphicsmagick调整图像大小。 我的代码如下(res是从函数(req,res){…}发送的响应)-

    imageURLPromise
    .then(function(response) {
        var  body = response.body;
        if (body) {
        console.log("Found From: " + response.request.uri.href);
    
        //set response headers here
        setResponseData(res, response);
    
    
        var buf = new Buffer(body, "binary");
        console.log(buf);
        //gm module
        gm(buf).resize(400,300).toBuffer(function(err,buffer) {
            console.log("buffer here");
            res.end(buffer, "binary");
        });
        }
    }, function(error) {
          console.log(error);
    });
    

    我在浏览器中获取图像,在这里获取日志“缓冲区”,但浏览器仍处于“加载”状态。

    我曾尝试将.stream()与gm一起使用,并将stdout通过管道发送到响应,但它也有同样的问题。

    如果我不使用gm,直接将body写到这样的响应中

    res.end(body, 'binary');
    

    那么它工作正常。

    有人能告诉我我做错了什么吗?

    1 回复  |  直到 10 年前
        1
  •  2
  •   Rahul Nanwani    10 年前

    我解决了这个问题。 问题不在于node或gm,而在于HTTP响应头。

    当GM返回缓冲区并将其写入HTTP响应时,它会将传输编码头设置为“分块”。在这种情况下,绝不应设置Content-Length标头。 你可以在这里阅读更多 http://en.wikipedia.org/wiki/Chunked_transfer_encoding

    由于我设置了这两个浏览器,所以即使在图像发送后,浏览器仍在等待内容。

    代码与我发布的代码完全相同,只是在setResponseData()函数(基本上用于设置标头)中,我现在没有设置内容长度标头。