Node.js为组织快速导出路由?

Sta*_*cks 3 javascript routes node.js express

利用express.Router()对我们的应用程序进行API调用:

var express = require('express');
var app     = express();
var router  = express.Router();
Run Code Online (Sandbox Code Playgroud)

router.use 每次API调用之前的console.logs:

router.use(function(req, res, next) { // run for any & all requests
    console.log("Connection to the API.."); // set up logging for every API call
    next(); // ..to the next routes from here..
});
Run Code Online (Sandbox Code Playgroud)

我们如何folder/routes.js从我们当前所在的主app.js导出我们的路线并从中访问它们:

router.route('/This') // on routes for /This
    // post a new This (accessed by POST @ http://localhost:8888/api/v1/This)
    .post(function(req, res) {
        // do stuff
    });

router.route('/That') // on routes for /That
    // post a new That (accessed by POST @ http://localhost:8888/api/v1/That)
    .post(function(req, res) {
        // do stuff
    });
Run Code Online (Sandbox Code Playgroud)

...当我们为每条路线添加前缀时:

app.use('/api/v1', router); // all of the API routes are prefixed with '/api' version '/v1'
Run Code Online (Sandbox Code Playgroud)

Ton*_*nes 8

在新的路径模块(例如,在api/myroutes.js)中,导出模块module.exports = myRouter;

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

router.use(function(req, res, next) { // run for any & all requests
  console.log("Connection to the API.."); // set up logging for every API call
  next(); // ..to the next routes from here..
});

router.route('/This')
  .get(function(req, res) { });
  .post(function(req, res) { });

...

module.exports = myRouter;
Run Code Online (Sandbox Code Playgroud)

然后,您可以在主服务器/应用程序文件中要求该模块:

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

...

var myRoutes = require('./api/myRoutes');

app.use('/api', myRoutes); //register the routes
Run Code Online (Sandbox Code Playgroud)