【问题标题】:Node crash using express and static middleware when URL contains a trailing backslash当 URL 包含尾部反斜杠时,使用快速和静态中间件的节点崩溃
【发布时间】:2012-01-07 01:05:51
【问题描述】:

我有一个简单的 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/indlocalhost: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 connect express


    【解决方案1】:

    这种行为的原因似乎是fs.statfs.createReadStream 处理尾部反斜杠的方式不同。

    当字符串'path/to/public/index.html\\'is given to fs.stat在静态中间件中时,它会被忽略(在命令行上运行stat index.html\会检查名为index.html的文件,你必须为@987654330运行stat index.html\\ @)。所以fs.stat 认为文件被找到是因为它认为你在请求index.html,并且不会调用下一个中间件处理程序。

    稍后,那个字符串is passed to fs.createReadStream 认为它正在寻找index.html\。它没有找到该文件并抛出上述错误。

    由于函数对反斜杠的处理方式不同,您只能使用一些中间件过滤掉这些请求。

    【讨论】:

    • 看起来这是连接中的一个错误,因为让每个人都编写自定义中间件没有多大意义。尤其是因为那些不会轻易拒绝攻击服务的人。我会提交一个错误。谢谢!
    • 此问题现已在当前的 Connect 代码库中得到修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2012-06-07
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多