sendFile
用于发送文件,它还会从文件中推断出一些有趣的头信息(如内容长度)。对于 HEAD
请求,最理想的情况是我只想要完全相同的头信息,但跳过正文。
API 中似乎没有这个选项。也许我可以在响应对象中覆盖某些内容以阻止它发送任何内容?
以下是我的代码:
res.sendFile(file, { headers: hdrs, lastModified: false, etag: false })
有人解决了这个问题吗?
sendFile
方法已经具备了在请求方法为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
<
这是相同的内容,但没有正文。
server.head
映射到与server.get
相同的函数中,您最终会在head请求上发送body。 - Martin Algesten