[英]Node Connect Static set Content-type text/plain not working
I am trying to set the content type of the files served by connect.static to text/plain
. 我正在尝试将connect.static提供的文件的内容类型设置为text/plain
。 I thought this would work, but connect seems to still be detecting the content type fomr the extension with the mime
module. 我认为这会起作用,但是连接似乎仍然在检测mime
模块扩展的内容类型。
var connect = require("connect")
connect()
.use(connect.static(__dirname + "/public"))
.use(function(req, res, next) {
res.setHeader("Content-Type", "text/plain");
})
.listen(process.env.PORT);
Is there any easy way of doing this? 这有什么简单的方法吗? Maybe screwing around in connects instance of mime before it can get to it? 也许在连接mime的实例之前搞砸了才能到达它? Or will I have to rewrite connects static middleware? 或者我是否必须重写连接静态中间件?
If you have control of the filenames within the public directory, the easiest approach is to ensure that they end in '.txt', so that the mime map provides the send function with the correct Content-Type. 如果您可以控制公共目录中的文件名,最简单的方法是确保它们以“.txt”结尾,以便mime映射为send函数提供正确的Content-Type。
Failing that, you could change the default mime type: 如果失败,您可以更改默认的mime类型:
var connect = require("connect")
var mime = connect.static.mime;
mime.default_type = mime.lookup('text');
connect()
.use(connect.static(__dirname + "/public"))
.listen(process.env.PORT);
Alternatively, if you really want every file served as text/plain, just set the Content-Type header before the static middleware is invoked. 或者,如果您确实希望每个文件都作为text / plain提供,只需在调用静态中间件之前设置Content-Type标头。 It only adds the header if it isn't already present on the response: 如果标题尚未出现在响应中,它只会添加标题:
var connect = require("connect")
connect()
.use(function(req, res, next) {
res.setHeader("Content-Type", "text/plain");
next();
})
.use(connect.static(__dirname + "/public"))
.listen(process.env.PORT);
Only if the static middleware is not able to handle the request ,then the next middleware is executed. 只有静态中间件无法处理请求,才会执行下一个中间件。
Incase static middleware finds the file , it serves it to the client.Next middleware is not executed. Incase静态中间件找到该文件,它将它提供给客户端。下一个中间件不会被执行。
That is the reason why your middleware is not effective. 这就是您的中间件无效的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.