我有一个简单的 Express 服务器,它提供一些静态文件。这是服务器:
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);
在我的公共(public)目录中,有一个名为 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
页面?我认为由于该文件不存在,静态中间件只会跳过它并将请求传递到路由。我通过创建一个自定义中间件来解决这个问题,如果请求 URL 中存在尾部反斜杠,该中间件将返回 404
,但我想弄清楚我是否在这里遗漏了某些内容。谢谢!
最佳答案
此行为的原因似乎是 fs.stat
和 fs.createReadStream
处理尾部反斜杠的方式不同。
当字符串'path/to/public/index.html\\'
is given to fs.stat
在静态中间件中,它被忽略(在命令行上运行 stat index.html\
检查名为 index.html
的文件,您必须运行 stat index.html\\
为 index.html\
)。因此,fs.stat
认为该文件已找到,因为它认为您正在请求 index.html
,并且不会调用下一个中间件处理程序。
稍后,该字符串 is passed to fs.createReadStream
它认为它正在寻找 index.html\
。它找不到该文件并抛出所述错误。
由于这些函数以不同的方式处理反斜杠,因此您实际上无法做任何事情,只能使用一些中间件来过滤掉这些请求。
关于node.js - 当 URL 包含尾部反斜杠时,使用 Express 和静态中间件的 Node 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8766465/