Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express middleware to modify requests

i currently have a running server using nodejs, mongo, express and W2UI for the front end. W2ui requests come in an a record array that has all the parameters record[name]:foo i want to write a middleware that edits requests and changes them before they reach the route.

like image 647
motchezz Avatar asked Jan 31 '17 11:01

motchezz


Video Answer


1 Answers

You can create your own middleware to manipulate the request. I've created a middleware that adds current server time to the request like this

var addDate = function(req, res, next) {
  req.body.date = new Date();
  next();
}

Now, I can use this middleware for all requests like this:

app.use(addDate);

or to a spesific route like this

app.get('/', addDate, function(req, res) {
  res.send(req.body);
});

The response from the get request will be

{
  "date": "2017-01-31T11:46:37.003Z"
}
like image 57
R. Gulbrandsen Avatar answered Sep 28 '22 23:09

R. Gulbrandsen