MrC*_*oft 3 redirect express angular-universal angular
我有我的 ssr 响应服务,其中包括重定向方法:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在我的组件中,如果不满足某些条件,我需要重定向用户:
this.responseService.redirect('/some-other-url', 301);
Run Code Online (Sandbox Code Playgroud)
重定向工作正常,用户被重定向,但服务器记录:
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.
Run Code Online (Sandbox Code Playgroud)
完整堆栈跟踪:https://gist.github.com/MrCroft/c8a659567a3b248744b62a7cc04f061d
我可以采取哪些不同的措施来避免该错误?请注意,该决定只能在 Angular 应用程序代码中做出。
我遇到了同样的问题并找到了解决方法:
而不是使用this.response.redirect(url, code)
使用:
this.response.status(code)
this.response.setHeader('Location', url);
Run Code Online (Sandbox Code Playgroud)
错误消失
归档时间: |
|
查看次数: |
1920 次 |
最近记录: |