【问题标题】:Use express sendFile for HEAD requests对 HEAD 请求使用 express sendFile
【发布时间】:2017-09-06 15:47:51
【问题描述】:

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

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

这是我得到的:

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

有人解决了吗?

【问题讨论】:

  • 您不能使用该方法并仅请求标头吗?或者我可能不了解您的需求。
  • 如果您映射 server.head 以进入与 server.get 相同的功能,您最终也会在头部请求中发送正文。

标签: node.js http express


【解决方案1】:

正如 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'));

这会在 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
< 

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

【讨论】:

  • 嗯。这是一个比我已经接受的@robertklep 更详尽的答案。切换格式不好吗?
  • @MartinAlgesten 作为刚刚提出您问题的人,我不这么认为。我宁愿看到最有帮助的答案被标记为最佳答案。
【解决方案2】:

Express 使用send 来实现sendFile,而exactly what you want 已经实现了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2011-12-11
    • 1970-01-01
    • 2018-03-01
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多