sendFile是用来发送文件的,它还从文件中找出了一些有趣的头(比如内容长度)。对于HEAD请求,理想情况下,我希望得到完全相同的头,但跳过主体。
在API中似乎没有这方面的选项。也许我可以覆盖响应对象中的什么东西来阻止它发送任何东西?
我得到的是:
res.sendFile(file, { headers: hdrs, lastModified: false, etag: false })有人解决过这个问题吗?
发布于 2017-04-11 10:47:50
正如Robert已经写过的那样,如果请求方法是HEAD,sendFile已经具备了发送头部而不是发送主体的必要行为。
除此之外,Express已经处理已定义了GET处理程序的路由的头请求。因此,您甚至不需要显式地定义任何头处理程序。
示例:
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
< 这是一样的,但没有身体。
https://stackoverflow.com/questions/43342836
复制相似问题