使用express.Router()处理与应用程序的API调用:
var express = require('express');
var app = express();
var router = express.Router();
router.use
在每次 API 调用之前打印日志:
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'
module.exports = router;
而不是module.exports = myRouter;
? - 76484