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

使用nodemon运行Express项目时出现Router.use()类型错误求助

Express项目中Router.use()类型错误的排查与解决

错误信息

throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

完整错误栈:

TypeError: Router.use() requires a middleware function but got a Object
    at Function.use (C:\Users\wBk\StudioProjects\devmob\lib\flutter\backend\node_modules\express\lib\router\index.js:469:13)
    at Function.<anonymous> (C:\Users\wBk\StudioProjects\devmob\lib\flutter\backend\node_modules\express\lib\application.js:227:21)
    at Array.forEach (<anonymous>)
    at Function.use (C:\Users\wBk\StudioProjects\devmob\lib\flutter\backend\node_modules\express\lib\application.js:224:7)
    at Object.<anonymous> (C:\Users\wBk\StudioProjects\devmob\lib\flutter\backend\index.js:14:5)
    at Module._compile (node:internal/modules/cjs/loader:1358:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)
    at Module.load (node:internal/modules/cjs/loader:1208:32)
    at Module._load (node:internal/modules/cjs/loader:1024:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)

Node.js v20.16.0
[nodemon] app crashed - waiting for file changes before starting...

相关代码

index.js

const express = require('express')
const app = express()
const port = 8080 || process.env.PORT
const cors = require('cors')
const bodyParser = require('body-parser')

const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/mydb")

app.use(cors())
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())

app.listen(port,()=>{
    console.log('port running on '+port)
})

router.js

const express = require('express')
const User = require('../models/user.model')
const router = express.Router()

router.post('/signin',(req,res)=>{
   console.log('hello world')
})

module.exports = router

错误原因分析

从错误栈可定位到index.js第14行的app.use()调用传入了对象而非中间件函数/Express Router实例。结合代码,可能的场景包括:

  • 实际的index.js中存在未展示的app.use()调用,传入了非函数类型参数(比如错误挂载mongoose对象、配置对象等)
  • 尝试挂载router.js的路由,但未正确引入模块或挂载方式错误(比如路径错误、导出的路由实例格式有误)

解决方法

  1. 检查index.js第14行代码
    找到该行的app.use()调用,确认传入参数是中间件函数(如cors()、bodyParser.json()这类返回函数的调用)或Express Router实例,避免直接传入普通对象。

  2. 正确挂载路由(若需使用router.js)
    如果要启用router.js中的路由,在index.js的app.use(bodyParser.json())之后补充代码:

    const router = require('./router') // 确保路径与router.js实际位置匹配
    app.use('/api', router) // 可指定路由前缀,也可直接写app.use(router)
    
  3. 验证路由模块导出
    确认router.js的导出方式正确:

    // 直接导出Router实例,不要包裹在对象中
    module.exports = router
    
  4. 排查其他错误挂载
    检查所有app.use()调用,避免将非中间件函数的对象(比如mongoose、未调用的中间件模块)传入,例如错误写法app.use(mongoose),正确写法应为仅挂载返回函数的中间件调用。

内容的提问来源于stack exchange,提问作者wael wbk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:13:15