NodeJS stream.listener不是函数

drkbr07n  于 2022-11-29  发布在  Node.js
关注(0)|答案(1)|浏览(181)

尝试运行一个非常基本的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)

应用程序代码实际上就是:

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中没有看到该错误消息。

qco9c6ql

qco9c6ql1#

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

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

会呼叫app。程式码应该呼叫app的其中一个 * 方法 *,例如app.get

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

虽然没有文档记录,但是app(函数)调用app.handle

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

app.handle需要与app.get非常不同的参数。向其传递app.get参数会使其最终到达错误条件。
只需将app(更改为app.get(或代码要使用的任何其他方法。

相关问题