当URL包含尾部反斜杠时,节点使用快速和静态中间件崩溃
我有一个简单的服务器提供一些静态文件。 这是服务器:
var express = require('express'); var app = express.createServer(); // Configuration app.configure(function() { app.use(express.bodyParser()); app.use(express.staticCache()); app.use(express.static(__dirname + '/public')); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); // 404 app.get('*', function(req, res) { res.send('not found', 404); }); app.listen(3000);
在我的公共目录中,我有一个名为index.html
的文件。 启动node app.js
,然后浏览到localhost:3000/index.html
将按预期显示静态文件。 导航到localhost:3000/ind
或localhost:3000/ind\
按预期显示404
页面。
但是,导航到localhost:3000/index.html\
(注意尾部反斜杠)崩溃我的node
服务器:
stream.js:105 throw er; // Unhandled stream error in pipe. ^ Error: ENOENT, no such file or directory '/home/bill/projects/app/public/index.html\'
为什么node
服务器崩溃,而不是只提供404
页面? 我以为文件不存在,静态中间件会跳过它,并将请求传递给路由。 我通过创build一个自定义中间件来解决这个问题,如果请求URL中存在一个尾部的反斜杠,将返回404
,但是我想知道是否在这里丢失了一些东西。 谢谢!
这种行为的原因似乎是fs.stat
和fs.createReadStream
处理反斜线的区别。
当string'path/to/public/index.html\\'
被赋予静态中间件中的fs.stat
时,将被忽略(在命令行上运行stat index.html\
将检查名为index.html
的文件,你必须运行stat index.html\\
index.html\
)。 所以fs.stat
认为这个文件被find了,因为它认为你在fs.stat
index.html
,而不会调用下一个中间件处理程序。
稍后,该string被传递给fs.createReadStream
,它认为它正在寻找index.html\
。 它没有find该文件并抛出所述错误。
由于函数对待反斜杠的方式不同,因此除了使用一些中间件来过滤这些请求之外,您无法做任何事情。