Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Universal 404 Not Found redirection

I'm implementing a route guard (CanActivate interface) and I need to redirect to not found page under certain conditions. This can be achieved with the following sentence:

if (isNode){
let res : Response = Zone.current.get('res');
res.status(404).redirect('/not-found');
}else{
this.router.navigate(['not-found']);
}

This works, but raises an exception server side (Error: Can't set headers after they are sent), because angular2-universal still sends the rendered page, regardless of the redirection.

Is there any way to solve this properly?

Thanks in advance.

like image 363
José Millán Medina Avatar asked Oct 30 '22 12:10

José Millán Medina


1 Answers

There is actually a solution for bypassing the error.

In server.ts in the res.render method add callback function and check for res.headersSent boolean.

server.get('*', (req, res) => {
  res.render('../public/index.html', {req, res},
    (error, html) => {
      if(error)
        // error handle
      if (!res.headersSent) {
        res.send(html);
      }
    });
});

Obviously, send the html only if res.headersSent is false.

like image 115
pbibergal Avatar answered Jan 02 '23 21:01

pbibergal