2

I'm building an API in node.js with express, and I would like to extend the basic res.send from ANY of the external route files before a response is sent, as to pre-format the response and append in additional data. How is this possible? Thanks in advance!

willium
  • 2,048
  • 5
  • 25
  • 34

1 Answers1

1

That's the purpose of middleware. See http://expressjs.com/api.html#middleware

For example, these lines activate the CSRF middleware and then make the CSRF token available to templates and generate the CSRF cookie used by AngularJS:

.use(express.csrf())
.use(function (req, res, next) {
  res.cookie('XSRF-TOKEN', req.session._csrf);
  res.locals.csrftoken = req.session._csrf;
  next();
})
Dan Kohn
  • 33,811
  • 9
  • 84
  • 100
  • I don't understand how that's related. – willium Aug 17 '13 at 06:52
  • Following my example, "pre-format the response" where I set a cookie and use res.locals to "append in additional data". This will then be available to all routes. – Dan Kohn Aug 17 '13 at 10:16