node.js - 当 URL 包含尾部反斜杠时,使用 Express 和静态中间件的 Node 崩溃

标签 node.js connect express

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

最佳答案

此行为的原因似乎是 fs.statfs.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/

相关文章:

mysql - 环回 - ACL - 'property' DB 表中的默认值?

node.js - ElectronJS - 将文件夹添加到收藏夹 [macOS]

node.js - 在 Windows 7 上找不到模块 'connect'

node.js - 如何在跨源请求中保留 session 数据?

javascript - NodeJS 内存泄漏

javascript - 在我返回 res.end() 之后,Promise 仍然会转到下一个链

windows - Windows 上的 Node.js 和文件系统 - EBUSY 错误

performance - 每个事务的连接/断开连接的 Oracle 性能

javascript - 来自 Amazon S3 的 res.download 文件

node.js - React webapp在PROD环境中不断加载本地主机资源