Nest JS Controller, Http Request and Response

Controller

controller are responsible for handling request in nest js

import { Controller, Get, Header, HttpCode, HttpStatus, Req } from "@nestjs/common";
import { Request } from "express";

@Controller('/users')
export class UsersController {

    // All request handler related to /users route will be there

    // request handler for get profile '/users/profile'
    @Get('/profile')
    getProfile(@Req() req : Request) {
        // you can object request object here
        console.log(req.body)
        return { data: { name: 'saurabh' }}
    }
}

here this controller responsible for /users request and there is one controller handle for /users/profile

there is the way you can get anything from the request object

Response and HTTP Status

import { Controller, Get, Header, HttpCode, HttpStatus, Req } from "@nestjs/common";
import { Request } from "express";

@Controller('/users')
export class UsersController {
    @Get('/wallet')
    @HttpCode(HttpStatus.OK)
    @Header('no-cache', 'none')
    getProfileData(){
        return { data: []}
    }
}

this is the way you can change status code of response and header.

Access route params from route

import { Controller, Get, Header, HttpCode, HttpStatus, Param, Req } from "@nestjs/common";
import { Request } from "express";

@Controller('/users')
export class UsersController {

    @Get('/wallet/:id')
    @HttpCode(HttpStatus.OK)
    @Header('no-cache', 'none')
    getProfileData(@Param('id') id: string){
        // you can get id here
        console.log(id)
        return { data: []}
    }
}

Access query params

import { Controller, Get, Header, HttpCode, HttpStatus, Param, Query, Req } from "@nestjs/common";
import { Request } from "express";

@Controller('/users')
export class UsersController {
    @Get('/wallet')
    @HttpCode(HttpStatus.OK)
    @Header('no-cache', 'none')
    getProfileData(@Query('name') name: string){
        console.log(name)
        return { data: []}
    }
}

Access body in nest js

import { Body, Controller, Get, Header, HttpCode, HttpStatus, Param, Post, Query, Req } from "@nestjs/common";
import { Request } from "express";

interface userDTO {
    name: string,
    email: string
}

@Controller('/users')
export class UsersController {
    @Post('/create')
    @HttpCode(201)
    createUser(@Body() data: userDTO) {
        console.log(data)
        return 'created'
    }
}

Did you find this article valuable?

Support SAURABH TARAGI by becoming a sponsor. Any amount is appreciated!