如何使用 NestJS 获取 FullURL?

alc*_*imb 8 nestjs

如何获取 NestJS 正在处理的页面的完整 URL?(例如http://localhost:3000/hoge)

// 
// If you implement it with express, it looks like this.
// e.g. http://localhost:3000/hoge
// 
function getFullUrl(req: express.Request) {
  return `${req.protocol}://${req.get('Host')}${req.originalUrl}`;
}
Run Code Online (Sandbox Code Playgroud)

eol*_*eol 24

Req() 您可以使用装饰器注入请求对象,这样您就可以执行与纯 Express 应用程序中几乎相同的操作。

import {Controller, Get, Req} from '@nestjs/common';
import {Request} from 'express';

@Controller()
export class AppController {    
    @Get()
    getHello(@Req() req: Request): void {
        console.log(`${req.protocol}://${req.get('Host')}${req.originalUrl}`);
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,这假设您使用 Express 作为http 适配器(这是默认设置)。

  • **这个答案对我很有帮助。**非常感谢。据了解,这是基于使用Express HTTP适配器的前提。 (2认同)