5

我想将用户重定向到我服务器中的另一个 url,但我不想硬编码res.redirect('/hello_world'). 相反,我只想指定指定控制器的处理程序 url,例如res.redirect(HelloWorldController.handlerName.url)HelloWorldContoller 所在的位置

@Controller()
export class HelloWorldController {
    @Get('hello_world')
    handlerName(): string {
        return 'Hello World!';
    }
}
4

1 回答 1

4

例如,您可以使用Reflect来获取如下元数据:

import { PATH_METADATA } from '@nestjs/common/constants';

@Controller('api')
export class ApiController {
  @Get('hello')
  root() {
    let routePath = Reflect.getMetadata(PATH_METADATA, StaticController);
    routePath += '/' + Reflect.getMetadata(PATH_METADATA, StaticController.prototype.serveStatic);
    console.log(routePath); will return `api/hello`
    return {
      message: 'Hello World!',
    };
  }
}
  1. 我们得到 api 元数据
  2. 然后是方法

如果我需要的路径不是自己的 url,而是其他控制器的 url,为什么它会返回 api/hello?

这里StaticController用作示例,您可以导入任何其他控制器并将其传递给Reflect.getMetadata(PATH_METADATA, AnyOtherController);

于 2018-04-20T11:53:26.747 回答