Nestjs @Redirect()装饰器无法覆盖重定向url,Location为空问题求助
问题原因与解决方法
核心问题出在NestJS版本兼容与@Redirect()装饰器的使用规则上:
- 部分低版本
@nestjs/common存在已知bug:当@Redirect()装饰器未传入默认参数时,会忽略路由方法返回的动态重定向配置,直接使用空地址作为重定向目标 - 部分稳定版本也要求
@Redirect()必须传入占位默认值,才会触发后续的动态重定向逻辑
修复方案1:升级依赖+补充装饰器默认参数
- 先升级NestJS核心依赖到最新稳定版
npm update @nestjs/common @nestjs/core
- 修改路由代码,给
@Redirect()传入占位默认参数即可,原有逻辑无需修改:
import { Get, Query, Redirect, Session } from '@nestjs/common' import { ConfigService } from '@nestjs/config' @Controller('auth') export class AuthController { // 确保ConfigService已正确注入,你当前能打印出url说明这步已经正常完成 constructor(private configService: ConfigService) {} @Get('/callback') // 传入占位的空字符串和默认302状态码即可 @Redirect('', 302) async authCallback() { const url = this.configService.get<string>('AUTH_REDIRECT_URL'); console.log(url); // 该返回值会自动覆盖装饰器的默认参数 return { url }; } }
修复方案2:兜底手动控制重定向
如果方案1仍不生效,可以直接注入原生响应对象手动处理重定向,完全绕过@Redirect()装饰器的规则限制:
import { Get, Query, Session, Res } from '@nestjs/common' import { ConfigService } from '@nestjs/config' import { Response } from 'express' @Controller('auth') export class AuthController { constructor(private configService: ConfigService) {} @Get('/callback') async authCallback(@Res() res: Response) { const url = this.configService.get<string>('AUTH_REDIRECT_URL'); return res.redirect(url); } }
内容的提问来源于stack exchange,提问作者Bstorm
相关产品推荐
相关产品推荐

