的router
在express
是middleware
所以,當你定義你的路由的順序是非常重要的。爲了分離API路由,您可以創建一個模塊來處理這些模塊,然後創建middlewares
以捕獲其他路由,其中包括一個用於404響應的路由。不要忘記首先放置api路線。這是一個例子:
var express = require('express');
...
var routes = require('./routes/api');
var app = express();
...
// handle the request for the API
app.use('/api', routes);
...
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
和API路線模塊:
var express = require('express');
var router = express.Router();
/* GET test page. */
router.get('/test/:x/:y', function(req, res, next) {
res.render('test', { x: req.params.x, y: req.params.y });
});
module.exports = router;
您可能還想看看react-project如何處理:https://github.com/ryanflorence/react-project/blob/v0.0.30/modules/PublicServerAPI.js#L103-L134 –