You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行基础Express应用时出现TypeError: stream.listeners is not a function错误求助

问题:Express基础应用报错TypeError: stream.listeners is not a function

运行极简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

已在package.json中添加"type": "module",但移除该配置改用require后问题依旧,且未在Express的issues中找到相关报错。


解答

错误根源是路由注册方式写错了:直接调用app("/", ...)是错误的,这相当于调用了Express内部的app.handle方法(用于处理请求的核心方法),而非注册路由。这种错误调用会导致内部处理流程紊乱,最终触发stream.listeners is not a function的异常。

正确的做法是使用HTTP方法对应的路由注册函数,比如app.get(处理GET请求):

import express from "express";

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

// 修正为app.get注册GET路由
app.get("/", (req, res) => {
    res.send("Is this thing on?");
});

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

如果需要匹配所有HTTP方法,可以用app.all("/", ...);针对其他方法(POST/PUT等),则使用对应的app.post/app.put等方法即可。


内容的提问来源于stack exchange,提问作者T.J. Crowder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:40:31