简体   繁体   中英

Express js - Use routes in separate file

I'm trying to setup a node project and I want to put a file routes.js in routes/routes.js and controllers files in controllers/ directory.

So, for example I have the UserController like this:

var index = () =>
{
  console.log("User Index");
};
var getUser = (id) => {
  console.log("User by id " + id);
};

module.exports =
{
  index,
  getUser
}

And in routes.js I have this:

    var express = require('express');
var routes = express.Router();
var users = require('../controllers/usersController');


routes.route('/')
  .get(users.index);

routes.route('/user/:userId')
  .get(users.getUser);


module.exports=
{
  routes
};

And in index.js I'm setup in this way:

    let express = require('express');
let app = express();
let routes = require('./routes/routes');

app.set("views", './views');
app.set("view engine", 'jade');


app.use(express.static(__dirname + '/public'));

app.use('/', routes.index);
// launch ======================================================================
app.listen(9001);

When I try to run the server I have this error:

.../node_modules/express/lib/router/index.js:458
  throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
  ^
  TypeError: Router.use() requires a middleware function but got a undefined

What is the problem how can I configure setup this in this way?

Thank you

Your userController will be like this.

 module.exports = {
        index: (req, res) => {
            console.log("User Index");
        },
        getUser: (req, res) => {
            console.log("User by id " + req.params.id);
        }
    }

Your routes file will be like this

var express = require('express');
var routes = express.Router();
var users = require('../controllers/usersController');

routes.get('/', user.index);
routes.get('/user/:userId', user.getUser);

module.exports = routes;

Your index file will be like this

let express = require('express');
let app = express();
let routes = require('./routes/routes');

app.set("views", './views');
app.set("view engine", 'jade');


app.use(express.static(__dirname + '/public'));
app.use('/', routes);

app.listen(9001);

In routes.js replace:

module.exports=
{
  routes
};

to

module.exports = routes;

in index.js

app.use('/', routes.index); to app.use('/', routes);

should works...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM