Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Express redirect

I have my ssr response service, with a redirect method among other:

import { Injectable, Inject } from '@angular/core';

import { Response } from 'express';
import { RESPONSE } from '@nguniversal/express-engine';

@Injectable()
export class SsrResponseService {
  constructor(@Inject(RESPONSE) private response: Response) {}

  redirect(url: string, code?: number) {
    if (!!code) {
      return this.response.redirect(code, url);
    } else {
      return this.response.redirect(url);
    }
  }
}

Then, in my component I need to redirect the user if some conditions aren't met:

this.responseService.redirect('/some-other-url', 301);

The redirect works fine, the user is redirected, but the server logs:

Unhandled Promise rejection: Can't set headers after they are sent. ; 
Zone: <root> ; Task: Promise.then ; Value: Error: Can't set headers after they are sent.

Full stack trace: https://gist.github.com/MrCroft/c8a659567a3b248744b62a7cc04f061d

What can I do differently to avoid the error? Note that the decision can only be made from within the Angular application code.

like image 544
MrCroft Avatar asked Jun 14 '26 00:06

MrCroft


1 Answers

I had the same issue and found a workaround for it:

Instead of using this.response.redirect(url, code) use:

this.response.status(code)
this.response.setHeader('Location', url);

Error vanishes

like image 133
yanivps Avatar answered Jun 16 '26 16:06

yanivps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!