node.js - 对 HEAD 请求使用 express sendFile

标签 node.js http express

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/

相关文章:

javascript - 你能制作一个在找到匹配项时失败而不是通过的 JavaScript 正则表达式吗?

HTTP 与不同主机保持事件状态

javascript - 处理 GET 路由上的 POST 请求 (express.js)

javascript - NodeJS + expressJS : server-side vs. 客户端html渲染

node.js - 如何在 Digital Ocean 上为 Unity 设置 Socket.io 服务器?

php - Node.js UDP 流

node.js - Cypher 查询返回匹配的 Node 和可选关系

javascript - 将网站重定向到 HTTPS 并进行有限重试?

http - HTTP 的源端口是如何确定的? NAT 中是否存在冲突?

javascript - 使用本地存储预填表格