将 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/