Building a REST API with NodeJs and Express: my goal is to implement the 2 simplest Middlewares
:
- The first one is going to log the incoming request
- The second one is going to log the processed response (which is a
JSON
)
The first middleware (in app.js)
function logReqMiddleware(req, res, next) {
log.info('>>> %s at %s', req.method, req.path);
next();
}
The second middleware (in app.js)
function logResponseMiddleware(req, res, next) {
log.info('<<< %s (%s)', JSON.stringify(res), res.status);
next();
}
The controller function (in apiController.js)
export var router = express.Router();
router.get('/', foo);
function foo(req, res, next) {
res.status(200).json({ stupidExample: true });
next();
}
Building the app (app.js)
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logReqMiddleware);
app.use('/api', apiController.router);
app.use(logResponseMiddleware);
var server = app.listen(3000, function(){ log.info('running'); });
Now, making a request at localhost:3000/api
says: can't set headers after they are sent
; this is the related super cool response my question is, is it incompatible to write json data with json()
and adding the second middleware? How can I solve this?