在 Express 4.x 中包括 API 条路线

Including API routes in Express 4.x

我正在通过 '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 文件列表:

    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. More info is available on Express Routing here.

完成的

A Router 只是一个迷你快递应用程序,您可以定义 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()

注入路由器

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