简体   繁体   English

Nest.Js 从一个控制器重定向到另一个

[英]Nest.Js Redirect from a controller to another

So I have this module:所以我有这个模块:

@Module({
  imports: [],
  controllers: [AppController, AnotherController],
  providers: [],
})

And in AppController on some route I want to do res.redirect('/books') where /books is a route found in AnotherController .AppController的某个路线上,我想做res.redirect('/books')其中/books是在AnotherController找到的路线。

For some reason this doesn't work and I can't figure out if it's not supported or I'm doing it wrong.出于某种原因,这不起作用,我不知道它是否不受支持或我做错了。

Redirecting from one controller to another works with res.redirect(target) .从一个控制器重定向到另一个控制器使用res.redirect(target) As target, you have to combine the paths from the controller and the route annotation:作为目标,您必须组合来自控制器的路径和路由注释:

@Controller('books') + @Get('greet') = /books/greet @Controller('books') + @Get('greet') = /books/greet

@Controller()
export class AppController {
  @Get()
  redirect(@Res() res) {
    return res.redirect('/books/greet');
  }
}

@Controller('books')
export class AnotherController {
  @Get('greet')
  greet() {
    return 'hello';
  }
}

See this running example here:在此处查看此运行示例:

编辑重定向控制器

Another way to do that is to use the @Redirect() decorator as documented here: https://docs.nestjs.com/controllers#redirection另一种方法是使用 @Redirect() 装饰器,如此处所述: https ://docs.nestjs.com/controllers#redirection

This should work as well:这也应该有效:

@Controller()
export class AppController {
  @Get()
  @Redirect('books')
  redirect(){}
}

@Controller('books')
export class AnotherController {
  @Get()
  getBooks() {
    return 'books';
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM