尝试运行真正基本的 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/