Nest.Js Redirect from a controller to another
17,009
Solution 1
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:
Solution 2
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';
}
}
Author by
Edeph
I'm a student in programming willing and eager to learn more .
Updated on June 15, 2022Comments
-
Edeph almost 2 years
So I have this module:
@Module({ imports: [], controllers: [AppController, AnotherController], providers: [], })
And in
AppController
on some route I want to dores.redirect('/books')
where/books
is a route found inAnotherController
.For some reason this doesn't work and I can't figure out if it's not supported or I'm doing it wrong.
-
Edeph almost 5 yearsThis is indeed the correct answer. What is weird is that I keep my controllers in 2 separate files and it doesn't work like that. It only works if i don't specify anything in the
@Controller()
and then write@Get('/books/greet')
. Which is weird because this is something that I understand is by default. -
Edeph almost 5 yearsApparently having another route like
/books/:id
written as@Get(':id')
was breaking it. -
Ctfrancia almost 3 yearsnote, this only works with
GET
method, any url provided with otherwise will be sent with a get first causing the endpoint not to be found