我有以下Express 4代码:
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var log = require('npmlog');
var httpStatus = require('http-status-codes');
var config = require('./config');
var routes = require('./routes');
app.use(function (err, req, res, next) {
log.verbose('Express', '%s %s', req.method, req.url); //Never called
next();
});
app.use(function (err, req, res, next) {
if(err) {
res.status(httpStatus.INTERNAL_SERVER_ERROR).send(err.message); //Never called
}
});
app.use(bodyParser.json());
app.use('/api', routes);
mongoose.connect(config.mongoAddress,
{keepAlive: 1, server: {auto_reconnect: true}},
function (err) {
if (err) {
log.error('Mongo', 'Could not connect to mongo database');
throw err;
} else {
log.info('Mongo', 'Successfully established connection to ' + config.mongoAddress);
}
}
);
var server = app.listen(config.port, function () {
log.info('Server', 'Server listening at %s', server.address().port);
});
我的路线工作正常,但我在app.use(bodyParser.json());
之前的所有功能都没有被调用(我也试过添加断点,但无济于事)。我也尝试在添加路线后添加这些功能,这没有帮助(但这是预期的)。
我忘了什么?
答案 0 :(得分:2)
这是怎么回事:
在定义中间件之前,您已经包含了路由。你应该做的是这样的事情:
var app = express();
// setup all middlewares here
app.use(...);
app.use(...);
// include all routes here
app.use(routera);
app.use(routerb);