Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

For some reason this doesn't work and I can't figure out if it's not supported or I'm doing it wrong.

like image 858
Edeph Avatar asked May 31 '19 15:05

Edeph


2 Answers

Redirecting from one controller to another works with 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()
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:

Edit Redirect-Controller

like image 162
Kim Kern Avatar answered Oct 17 '22 03:10

Kim Kern


Another way to do that is to use the @Redirect() decorator as documented here: 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';
  }
}
like image 1
user2436448 Avatar answered Oct 17 '22 04:10

user2436448