How to separate routes on Node.js and Express 4?

2019-01-07 06:43发布

问题:

I want to separate Routes from my server.js file.

I am following this tutorial on Scotch.io http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4

It is working if all lines are on server.js file. But I am failing to separate. How can I make this work?

server.js

// set up ======================================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// configuration ===============================================================
app.use(bodyParser());

var port = process.env.PORT || 8000;

var mongoose = require('mongoose');
var database = require('./config/database');
mongoose.connect(database.url);
var Video = require('./app/models/video');

// routes =======================================================================
app.use('/api', require('./app/routes/routes').router);

// listen (start app with node server.js) ======================================
app.listen(port);
console.log("ready captain, on deck" + port);

module.exports = app;

And the app/routes/routes.js

var express = require('express');
var router = express.Router();

router.use(function(req, res, next) {
  console.log('Something is happening.');
  next();
});

router.get('/', function(req, res) {
  res.json({ message: 'hooray! welcome to our rest video api!' });  
});


router.route('/videos')

  .post(function(req, res) {

    var video = new Video();
    video.title = req.body.title;

    video.save(function(err) {
  if (err)
    res.send(err);

  res.json({ message: 'Video criado!' });
});


  })

  .get(function(req, res) {
    Video.find(function(err, videos) {
      if (err)
        res.send(err);

      res.json(videos);
    });
  });

module.exports.router = router;

回答1:

As far as separating routes from main file is concerned..

Server.js

//include the routes file
var routes = require('./routes/route');
var users = require('./routes/users');
var someapi = require('./routes/1/someapi');

////////
app.use('/', routes);
app.use('/users', users);
app.use('/1/someapi', someapi);

routes/route.js

//last line - try this
module.exports = router;

Also for new project you can try on command line

express project_name

You will need express-generator for that



回答2:

Server.js

var express = require('express');
var app = express();

app.use(express.static('public'));

//Routes
app.use(require('./routes'));  //http://127.0.0.1:8000/    http://127.0.0.1:8000/about

//app.use("/user",require('./routes'));  //http://127.0.0.1:8000/user  http://127.0.0.1:8000/user/about


var server = app.listen(8000, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

})

routes.js

var express = require('express');
var router = express.Router();

//Middle ware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});


// Define the home page route
router.get('/', function(req, res) {
  res.send('home page');
});

// Define the about route
router.get('/about', function(req, res) {
  res.send('About us');
});


module.exports = router;

*In routs.js you should define Middle ware

ref http://wiki.workassis.com/nodejs-express-separate-routes/



回答3:

Another way to separate routes into their own files with Express 4.0:

server.js

var routes = require('./routes/routes');
app.use('/', routes);

routes.js

module.exports = (function() {
    'use strict';
    var router = require('express').Router();

    router.get('/', function(req, res) {
        res.json({'foo':'bar'});
    });

    return router;
})();


回答4:

One way to separate routes into their own file.

SERVER.JS

var routes = require('./app/routes/routes');  //module you want to include
var app=express();
routes(app);   //routes shall use Express

ROUTES.JS

module.exports=function(app) {
 //place your routes in here..
 app.post('/api/..., function(req, res) {.....}   //example
}


回答5:

An issue I was running into was attempting to log the path with the methods when using router.use ended up using this method to resolve it. Allows you to keep path to a lower router level at the higher level.

routes.js

var express = require('express');
var router = express.Router();

var posts = require('./posts');

router.use(posts('/posts'));  

module.exports = router;

posts.js

var express = require('express');
var router = express.Router();

let routeBuilder = path => {

  router.get(`${path}`, (req, res) => {
    res.send(`${path} is the path to posts`);
  });

  return router

}

module.exports = routeBuilder;

If you log the router stack you can actually see the paths and methods



回答6:

In my case, I like to have as much Typescript as possible. Here is how I organized my routes with classes:

export default class AuthService {
    constructor() {
    }

    public login(): RequestHandler {
       return this.loginUserFunc;
    }

    private loginUserFunc(req: Request, res: Response): void {
        User.findOne({ email: req.body.email }, (err: any, user: IUser) => {
            if (err)
                throw err;
            if(!user)
                return res.status(403).send(AuthService.noSuccessObject());
            else
                return AuthService.comparePassword(user, req, res);
        })
    }
}

From your server.js or where you have your server code, you can call the AuthService in the following way:

import * as express from "express";
import AuthService from "./backend/services/AuthService";

export default class ServerApp {
    private authService: AuthService;

    this.authService = new AuthService();

    this.myExpressServer.post("/api/login", this.authService.login(), (req: express.Request, res: express.Response) => {
    });
}