sendFile
用于发送文件,它还会从文件中找出一些有趣的 header (如内容长度)。对于 HEAD
请求,理想情况下我想要完全相同的 header ,但只是跳过正文。
API 中似乎没有这方面的选项。也许我可以覆盖响应对象中的某些内容以阻止它发送任何内容?
这是我得到的:
res.sendFile(file, { headers: hdrs, lastModified: false, etag: false })
有人解决了吗?
最佳答案
正如 Robert Klep 已经写过的,如果请求方法是 HEAD,sendFile
已经具有发送 header 而不发送正文的所需行为。
除此之外,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
<
这是相同的,但没有主体。
关于node.js - 对 HEAD 请求使用 express sendFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43342836/