0

I am currently trying to send a 404 page that is a .pug file whenever a an ID params is not in the database. I am calling next() in the api route, and when I do it inside the elastics search callback, it will throw a page not found error as well as two Cant set header after they are sent messages. When I call the next() outside, it will properly just show the 404 error message and not the header message. I am unsure of why it is doing this.

//Doing it this way will properly send the 404 page.

app.get('/redirect/:id', function(req, res, next) {
        let found = false;

        if (!found) {
           return next();
        }

});

//But i need to check if an ID exists and then throw the 404, but doing it this way will not work and I will keep getting an error about not being able to set headers and the 404 message.

app.get('/redirect/:id', function(req, res, next) {

    search.byId(req.params.id, (err, card) => {
        if (err) log.log(err);

        if (!card || card === undefined) {
            return next();
        }
    });

});
Jonas
  • 121,568
  • 97
  • 310
  • 388
henhen
  • 1,038
  • 3
  • 18
  • 36
  • Why ```next()```? You're done. ```res.status(404).end();``` will return your 404 – Wainage Jul 12 '17 at 23:05
  • okay I tried that, but it is still not sending my 404 page. In the shell, the set headers error messages won't show up anymore but also the 404 error page not found will not show. It does show a bunch of GET request are happnening with a 304 status – henhen Jul 12 '17 at 23:13
  • What's calling your end-point? Postman? – Wainage Jul 12 '17 at 23:16
  • It is elastic search. The search.byId is an elastic search method – henhen Jul 12 '17 at 23:23
  • What's calling your ```/redirect/:id```? Elastic search? – Wainage Jul 12 '17 at 23:30
  • For now, nothing, I am just directly typing it into the browser URL bar – henhen Jul 12 '17 at 23:32
  • Your browser is sending ```last-modified-since``` causing Express to return a 304 (nothing changed). Use a proper REST tool like Postman and turn off caching to test – Wainage Jul 12 '17 at 23:36
  • Okay, but then how come when I use next(), like in my first example, it will properly send the 404 page? – henhen Jul 12 '17 at 23:38

1 Answers1

0

In express, the next() function is for passing the control to the next middleware. Using Express Middleware

app.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}, function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

In the example above, when the first next() is called the second function (req, res, next) (in express.js terms the function is called middleware) got exectued and log out the request type. So next doesn't help you here since you are not building a middleware stack. If you just want to render 404 page read How to redirect 404 errors to a page in ExpressJS?

Hanzhao Deng
  • 118
  • 6