javascript - 组织的 Node.js Express 导出路线?

标签 javascript node.js express routes

将 express.Router() 用于我们应用程序的 API 调用:

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

router.use console.logs before every API call:

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..
});

我们如何将我们的路由导出到 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
    });

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

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

最佳答案

在您的新路由模块中(例如在 api/myroutes.js 中),导出该模块。

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

router.use(function(req, res, next) {
  console.log('Connection to the API..');
  next();
});

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


module.exports = router;

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

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


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

app.use('/api', myRoutes); //register the routes

关于javascript - 组织的 Node.js Express 导出路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284092/

相关文章:

mysql - 为什么mysql会抛出语法错误

node.js - nodejs express app.use 方法

javascript - 如何在 node/express 中管理配置

javascript - 使用 window.location 重定向不起作用

javascript - Greensock-DrawSVG

javascript - 将 React 组件与另一个组件包装在同一文件中

javascript - 如何查找选定元素或 ElementHandle 的后代元素?

javascript - 评估类构造函数中的参数

JavaScript getElementById 空值错误以及如何避免它

node.js - MongoDB中根据时间段获取数据