node.js - Stream.listeners 不是一个函数

标签 node.js express

尝试运行真正基本的 Express 应用程序时,我收到此错误:

/path/to/testserver/node_modules/unpipe/index.js:22
  var listeners = stream.listeners('data')
                         ^

TypeError: stream.listeners is not a function
    at hasPipeDataListeners (/path/to/testserver/node_modules/unpipe/index.js:22:26)
    at unpipe (/path/to/testserver/node_modules/unpipe/index.js:52:8)
    at send (/path/to/testserver/node_modules/finalhandler/index.js:311:3)
    at /path/to/testserver/node_modules/finalhandler/index.js:133:5
    at Function.handle (/path/to/testserver/node_modules/express/lib/application.js:177:5)
    at app (/path/to/testserver/node_modules/express/lib/express.js:39:9)
    at file:///path/to/testserver/index.js:6:1
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:530:24)

The app code is literally just:

import express from "express";

const port = 3000;
const app = express();

app("/", (req, res) => {
    res.send("Is this thing on?");
});

app.listen(port, () => {
    console.log(`Listening on ${port}...`);
});

我像这样启动了该项目:

npm init -y
npm install express

...然后将 "type": "module" 添加到 package.json (但我知道问题不是 ESM;我删除了它并切换了require 并遇到了同样的问题)。

为什么我会收到这个错误?我在 the issues list 中没有看到该错误消息.

最佳答案

这是一个拼写错误,但症状是如此奇怪,而且拼写错误如此微妙,值得在这里给出答案。问题出在这里:

    app("/", (req, res) => {
//  ^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
        res.send("Is this thing on?");
    });

调用 app 。该代码应调用 app 之一的方法,例如 app.get :

    app.get("/", (req, res) => {
//  ^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
        res.send("Is this thing on?");
    });

虽然看起来不是documented , app (函数)调用 app.handle 。来自 node_modules/express/lib/express.js :

var app = function(req, res, next) {
  app.handle(req, res, next);
};

app.handle期望的参数与 app.get 有很大不同做。恰巧路过它app.get参数将其引导至最终达到该错误条件的路径。

只需更改 app(app.get(或代码打算使用的任何其他方法。

关于node.js - Stream.listeners 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74558724/

相关文章:

node.js - 如何使用 Jade 在迭代中使用条件?

javascript - 获取express.js中所有登录用户的ID

javascript - 如何在不了解 Node/Browserify/npm 等知识的情况下使 Docxtemplater.js 在浏览器上工作?

angularjs - 使用适用于 Visual Studio 的 Angular 和 NodeJS 工具构建 NodeJS 应用程序

node.js - Express:从另一个中间件调用一个中间件

node.js - 尝试从 mongodb 格式化 DATE 时出现问题

node.js - Node (内存泄漏,v8 快照)- 使用连接 promise 是不好的做法吗?

node.js - 在 Swig 模板中使用 include 时连接变量和文件

node.js - 如何将一个字符串元素的数组折叠到其字符串中?

node.js - Sequelize JS,仅当存在多对多相关实体时才 findOne