【问题标题】:Express router : Router.use() requires a middleware function but got a ObjectExpress 路由器:Router.use() 需要一个中间件函数但得到一个对象
【发布时间】:2021-06-24 13:18:57
【问题描述】:

我知道 SO 中有很多问题,但没有一个给我解决方案

routes/authentication/index.js

import { Router } from 'express'

const router = Router();

router.get('/', (_req, _res) => console.log("Works"))

// module.exports = router                    <-- this works
export default router                      // <-- this doesn't

constants.js

const ROUTES = {
    'AUTHENTICATION' : require('../routes/authentication')
}

export default ROUTES

并在 app.js 中用作

import express from 'express'
import connectDatabase from './connectDb';
import ROUTES from './constants';
const app = express();

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
connectDatabase()

app.get('/', (_req, res) => {
  res.send("hello world")
})

app.use('/auth', ROUTES.AUTHENTICATION)

export default app;

现在 module.exports = router 可以工作,但 export default router 会引发错误

TypeError: Router.use() requires a middleware function but got a Object

我尝试找到问题的原因,但找不到。 提前致谢

【问题讨论】:

  • require constants.js 中的路由器文件,因此 module.exports 有效。
  • @Vishnudev 明白了。它奏效了。

标签: javascript node.js express express-router


【解决方案1】:

requireconstants.js 中的路由器文件,因此 module.exports 有效。

要使export default router 工作,您需要导入它。

【讨论】:

    猜你喜欢
    • 2019-12-23
    • 2018-04-30
    • 1970-01-01
    • 2016-02-13
    • 2015-07-08
    • 2020-12-06
    • 1970-01-01
    • 2015-02-12
    • 2018-09-27
    相关资源
    最近更新 更多