我正在通过“Getting MEAN with...”这本书学习 MEAN 堆栈,但问题是书中的 Express 版本比我使用的要旧。
The first step is to tell our application that we’re adding more routes to look out for, and when it should use them. We already have a line in app.js to require the server application routes, which we can simply duplicate and set the path to the API routes as follows:
var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');
Next we need to tell the application when to use the routes. We currently have the following line in app.js telling the application to check the server application routes for all incoming requests:
app.use('/', routes);
注意“/”是第一个参数。这使我们能够指定 URL 的子集 路线将适用。例如,我们将定义我们所有的 API 路由开始 与/api/。通过添加以下代码片段中显示的行,我们可以告诉应用程序仅当路由以/api 开头时才使用 API 路由:
app.use('/', routes);
app.use('/api', routesApi);
还有我的 app.js 文件的 list :
var express = require('express')
, others = require('./app_server/routes/others')
, locations = require('./app_server/routes/locations')
, routesApi = require('/app_api/routes/index')
, ;
require('./app_server/models/db')
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/app_server/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
// LOCATION PAGES
app.get('/', locations.homeList);
app.get('/location', locations.locInfo);
app.get('/location/review/new', locations.addReview);
// OTHER PAGES
app.get('/about', others.about);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
有人可以向我解释如何在我的 Express 版本中做同样的事情吗?
最佳答案
在 Express 4 中,这是使用 Router Middleware
完成的.有关更多信息,请访问 Express Routing here.
A Router
只是一个迷你 express 应用程序,您可以定义 middleware和上面的路由都应该打包在一起,即/api
都应该使用 apiRouter
.这是apiRouter
可能看起来像
apiRouter.js
var express = require('express')
var router = express.Router(); // Create our Router Middleware
// GET / route
router.get('/', function(req, res) {
return res.status(200).send('GET /api received!');
});
// export our router middleware
module.exports = router;
您的主要 Express 应用程序将保持不变,因此您将使用 require()
添加您的路由器导入实际文件,然后用 use()
注入(inject)路由器
Express 服务器文件
var express = require('express');
var app = express();
var apiRouter = require('../apiRouter');
var port = process.env.PORT || 3000;
app.use('/', apiRouter);
app.listen(port, function() {
console.log('listening on ' + port);
});
关于node.js - 在 Express 4.x 中包含 API 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37616050/