Edeph
Edeph

Reputation: 772

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.

Upvotes: 23

Views: 57242

Answers (2)

user2436448
user2436448

Reputation: 565

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';
  }
}

Upvotes: 4

Kim Kern
Kim Kern

Reputation: 60457

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

Upvotes: 38

Related Questions