Search code examples
node.jsexpressmiddleware

Applying a middleware function to particular requests


I want to apply a particular middleware function to the two post requests but not the get request. How could I do this?

var router = express.Router();
var app = express();

router.post('/jobs',(req,resp)=>{
  var messageString = JSON.stringify(req.body);
  Job.accept(messageString,(statusCode,respObject)=>{
    resp.status(statusCode).json(respObject);
  });
});

router.get('/jobs',(req,resp)=>{
  Job.status((statusCode,respObject)=>{     
      resp.status(statusCode).json(respObject);  
  });
});

router.post('/try',(req,resp)=>{
  var messageString = JSON.stringify(req.body);
  Job.ok(messageString,(statusCode,respObject)=>{
    resp.status(statusCode).json(respObject);
  });
});

I was reading about app.use, but couldn't really understand its usage.


Solution

  • Add the middleware you want to the function. Here is an example where I log the users IP

    const myLogger = (req, res, next) => {
      console.log('got a request from', req.connection.remoteAddress);
      next();
    }
    
    app.post('/jobs', myLogger, (req, res) => {
      //your code here...
    }