首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对头请求使用快捷sendFile

对头请求使用快捷sendFile
EN

Stack Overflow用户
提问于 2017-04-11 10:05:30
回答 2查看 3.4K关注 0票数 3

sendFile是用来发送文件的,它还从文件中找出了一些有趣的头(比如内容长度)。对于HEAD请求,理想情况下,我希望得到完全相同的头,但跳过主体。

在API中似乎没有这方面的选项。也许我可以覆盖响应对象中的什么东西来阻止它发送任何东西?

我得到的是:

代码语言:javascript
复制
res.sendFile(file, { headers: hdrs, lastModified: false, etag: false })

有人解决过这个问题吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-11 10:32:21

Express使用send来实现sendFile,后者已经实现了正是你想要的

票数 2
EN

Stack Overflow用户

发布于 2017-04-11 10:47:50

正如Robert已经写过的那样,如果请求方法是HEAD,sendFile已经具备了发送头部而不是发送主体的必要行为。

除此之外,Express已经处理已定义了GET处理程序的路由的头请求。因此,您甚至不需要显式地定义任何头处理程序。

示例:

代码语言:javascript
复制
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上发送自己的源代码,如下所示:

代码语言:javascript
复制
$ 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
< 
[...]

[...]是不包括在这里的身体。在不添加任何新的处理程序的情况下,这也可以工作:

代码语言:javascript
复制
$ 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
< 

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43342836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档