【发布时间】:2015-11-23 21:14:37
【问题描述】:
利用 express.Router() 对我们的应用程序进行 API 调用:
var express = require('express');
var app = express();
var router = express.Router();
router.useconsole.logs 在每次 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'
【问题讨论】:
标签: javascript node.js express routes