How to get FullURL with NestJS?

Viewed 2897

How do I get the full URL of the page that NestJS is processing? (e.g. 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}`;
}
1 Answers

You can inject the request-object using the Req() decorator allowing you to do pretty much the same thing you did in your pure express-app.

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}`);
    }
}

This of course assumes that you're using Express as your http-adapter (which is the default).

Related