1

我正在开发 javascript 应用程序,但我遇到了一些问题。

我想导出两个路由器,这是我的代码:

const {Router} = require('express')
const car = require('./car')
const user = require('./user')

// Routing
const routerCar = new Router()
routerCar.use('/car', car)
const routerUser = new Router()
routerUser.use('/user', user)
// 404 Error handler
routerCar.use((req, res, next) =>  res.status(404).send({error: 'Routing not found'}))
routerUser.use((req, res, next) =>  res.status(404).send({error: 'Routing not found'}))
// 500 Error handler
routerCar.use((err, req, res, next) =>  {
    console.error(err.stack)
    res.status(500).send({error: 'Server error'})
})
routerUser.use((err, req, res, next) =>  {
    console.error(err.stack)
    res.status(500).send({error: 'Server error'})
})


module.exports = {
    routerCar,
    routerUser
};

如果我只导出一个路由器,一切正常,例如:

module.exports= routerCar

但是,如果我要导出多个路由器:

module.exports = {
        routerCar,
        routerUser
    };

我收到错误。

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

这也是我的 app.js:

const http = require('http')
const { env, port, ip, apiRoot } = require('./config')
const express = require('./services/express')
const api = require('./api')    

const app = express(apiRoot, api)
const server = http.createServer(app)


setImmediate(() => {
  server.listen(port, ip, () => {
    console.log('Express server listening on http://%s:%d, in %s mode', ip, port, env)
  })
})


module.exports = app

和 index.js:

const express = require('express')
const bodyParser = require('body-parser')

const expressConfig = (apiRoot, routes) => {
  const app = express()

  app.use(bodyParser.json())  // obsluga dekodowania JSON
  app.use(apiRoot, routes)

  return app
}

module.exports = expressConfig

我怎样才能解决这个问题?先感谢您。

编辑:

'require('./car')' 的来源:

const { Router } = require('express')
const { createCar,showCars,updateCarById, showCarById ,destroyCarById,createReservationForCarId,showReservationByUserId,destroyReservationByUserId} = require('./controller')

const router = new Router()

router.post('/',
    createCar)

router.get('/',
    showCars)

router.get('/:id',
    showCarById)

router.put('/:id',
    updateCarById)

router.delete('/:id',
    destroyCarById)

router.put('/:id/reservation',
    createReservationForCarId)

router.get('/:id/reservation/:userID',
    showReservationByUserId)

router.delete('/:id/reservation/:userID',
    destroyReservationByUserId)

module.exports = router

对于用户:

const { Router } = require('express')
const {addUser,showUsers,showUserByID,updateUserByID,destroyUserByID} = require('./controller')

const router = new Router()

router.post('/',
    addUser)

router.get('/',
    showUsers)

router.get('/:id',
    showUserByID)

router.put('/:id/',
    updateUserByID)

router.delete('/:id',
    destroyUserByID)


module.exports = router
4

0 回答 0