当 URL 包含尾部反斜杠时,使用 Express 和静态中间件的节点崩溃

问题描述 投票:0回答:1

我有一个简单的 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);

在我的公共目录中,我有一个名为

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
,但我想弄清楚我是否在这里遗漏了某些内容。谢谢!

node.js express
1个回答
1
投票

这种行为的原因似乎是

fs.stat
fs.createReadStream
处理尾部反斜杠的方式不同。

当字符串

'path/to/public/index.html\\'
被赋予静态中间件中的
fs.stat
时,它会被忽略(在命令行上运行
stat index.html\
会检查名为
index.html
的文件,您必须运行
stat index.html\\
对于
index.html\
)。因此
fs.stat
认为该文件已找到,因为它认为您正在请求
index.html
,并且不会调用下一个中间件处理程序。

后来,该字符串 被传递给

fs.createReadStream
,它认为它正在寻找
index.html\
。它找不到该文件并抛出所述错误。

由于函数对反斜杠的处理方式不同,因此您实际上无法做任何事情,只能使用一些中间件来过滤掉这些请求。

© www.soinside.com 2019 - 2024. All rights reserved.