对 HEAD 请求使用 Express sendFile

Mar*_*ten 3 http node.js express

sendFile用于发送文件,它还可以从文件中找出一些有趣的标头(例如内容长度)。对于HEAD请求,我理想情况下想要完全相同的标头,但只是跳过正文。

API 中似乎没有此选项。也许我可以覆盖响应对象中的某些内容以阻止它发送任何内容?

这是我得到的:

res.sendFile(file, { headers: hdrs, lastModified: false, etag: false })
Run Code Online (Sandbox Code Playgroud)

有人解决这个问题了吗?

rsp*_*rsp 5

正如 Robert Klep 已经写的,sendFile如果请求方法是 HEAD,则已经具有发送标头而不发送正文的所需行为。

除此之外,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'));
Run Code Online (Sandbox Code Playgroud)

这会在 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
< 
[...]
Run Code Online (Sandbox Code Playgroud)

[...]是此处未包括的身体。在不添加任何新处理程序的情况下,这也将起作用:

$ 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
< 
Run Code Online (Sandbox Code Playgroud)

这是相同的,但没有身体。