对HEAD请求使用express sendFile

sendFile用于发送文件,并且还从文件中找出一些有趣的标题(如内容长度)。 对于HEAD请求,我会理想地想要完全相同的标题,但只是跳过正文。

在API中似乎没有这个选项。 也许我可以重写响应对象中的某些东西来阻止它发送任何东西?

这是我得到的:

 res.sendFile(file, { headers: hdrs, lastModified: false, etag: false }) 

有没有人解决这个?

Express使用send来实现sendFile ,它已经做到了你想要的 。

正如Robert sendFile已经写过的那样,如果请求方法是HEAD, sendFile已经具有发送标头和不发送主体的所需行为。

除此之外,Express已经处理了定义了GET处理程序的路由的HEAD请求。 所以你甚至不需要明确定义任何HEAD处理程序。

例:

 let app = require('express')(); let file = __filename; let hdrs = {'X-Custom-Header': '123'}; app.get('/file', (req, res) => { res.sendFile(file, { headers: hdrs, lastModified: false, etag: false }); }); app.listen(3322, () => console.log('Listening on 3322')); 

这可以在GET /file上发送自己的源代码,如下所示:

 $ curl -v -X GET localhost:3322/file * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 3322 (#0) > GET /file HTTP/1.1 > User-Agent: curl/7.35.0 > Host: localhost:3322 > Accept: */* > < HTTP/1.1 200 OK < X-Powered-By: Express < X-Custom-Header: 123 < Accept-Ranges: bytes < Cache-Control: public, max-age=0 < Content-Type: application/javascript < Content-Length: 267 < Date: Tue, 11 Apr 2017 10:45:36 GMT < Connection: keep-alive < [...] 

这是不包括在这里的身体。 不添加任何新的处理程序,这也将工作:

 $ curl -v -X HEAD localhost:3322/file * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 3322 (#0) > HEAD /file HTTP/1.1 > User-Agent: curl/7.35.0 > Host: localhost:3322 > Accept: */* > < HTTP/1.1 200 OK < X-Powered-By: Express < X-Custom-Header: 123 < Accept-Ranges: bytes < Cache-Control: public, max-age=0 < Content-Type: application/javascript < Content-Length: 267 < Date: Tue, 11 Apr 2017 10:46:29 GMT < Connection: keep-alive < 

这是一样的,但没有身体。