D
D
Dmitry Eremin2017-06-09 11:10:40
Node.js
Dmitry Eremin, 2017-06-09 11:10:40

How to write an intermediate handler?

Good afternoon. I look here and do as it is said, but something is wrong
The idea is that there are two routes [get] /:id and [get] /new/*
You need to write an intermediate handler so that the request is logged for both
routes to this code:

app.use(function (req, res, next) {
  console.log(new Date().toLocaleString('ru', options));
  console.log(req.originalUrl);
  console.log(req.params);
  console.log(JSON.stringify(req.body) || '-nobody');
  console.log('--------------------------------------');
  next();
});

app.get('/new/*', function(req, res){  
       console.log('1');
}) 

app.get('/:id', function(req, res){
    var id = req.params.id;
    if(id in list){
        console.log(list[id]);
        if (list[id].match('http')) { res.redirect(301, list[id]) }
        else                        { res.redirect(301, 'http://'+list[id]) }
    }
    else{
        res.status(404).send('no such element');
    }
})

Problem:
Requests are logged for the route app.get('/new/*')
AND logged for app.get('/:id'), but only if the logic in the handler reaches res.status(404).send(' no such element');
And if the condition is met and I send a redirect, the request is not logged.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rustler2000, 2017-06-09
@rustler2000

app.use('/',function (req, res, next) { -> app.use(function (req, res, next) {

C
Coder321, 2017-06-09
@Coder321

middleware work in order, are you sure that the routes you redirect to are after the logger?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question