Node.js设置错误的内容长度。 我如何设置这一个

我需要一些帮助。 即使我把内容长度设置为响应对象,它似乎不起作用。 我有错吗?

res.set({ 'Content-Type': res._data.ContentType, 'Content-Length': res._data.ContentLength, ETag: res._data.ETag }); res.send(res._data.Body); 

我使用express和body-parser来发送数据,并且我设置了Content-Length。

 res.header('Content-Type', res._data.ContentType); res.header('content-length', res._data.ContentLength); res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'); 

我也试过这个。

 { AcceptRanges: 'bytes', LastModified: 'Thu, 15 Jan 2015 22:23:43 GMT', ContentLength: '648789', ETag: '"7da971554e6ff4f6dfcdb7b2ba5e0be3"', ContentType: 'image/jpeg', Metadata: {}, Body: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff db 00 43 00 08 06 06 07 06 05 08 07 07 07 09 09 08 0a 0c 14 0d 0c 0b 0b 0c 19 12 13 0f 14 ...> } 

这是console.log(res._data) 。 正如你所看到的,我设置了内容长度。

 GET /api/images/54b83dec5e7d97c546e0c41a 200 584.524 ms - 1227943 

但是node.js以1227943的大小向客户端返回错误的内容长度。

 Cache-Control:no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0 Connection:keep-alive content-length:1227943 Content-Type:image/jpeg Date:Thu, 15 Jan 2015 23:37:52 GMT ETag:"7da971554e6ff4f6dfcdb7b2ba5e0be3" X-Powered-By:Express 

客户也收到。 有人知道我错过了什么? 请帮帮我。

哦,我忘了提到它。 当我使用邮差(铬扩展)来获取数据,它工作正常。

 GET /api/images/54b83dec5e7d97c546e0c41a 200 664.427 ms - 648789 

所以真的不知道为什么发生。

当您使用Express的response.send方法时,您无法手动设置Content-Length :该方法所做的最后一件事是基于(惊喜)发送Content-Length来设置Content-Length 。 您可以在源代码的send方法结尾看到:

https://github.com/strongloop/express/blob/4.11/lib/response.js

换句话说,Express是重写Content-Length

它看起来像res._data.ContentLength不反映缓冲区res._data.Body的大小。 检查一下res._data.Body.length是什么; 我猜是1227943