Introduction
Status codes and headers tell the browser or client what happened with the request and provide extra information.
Status codes and headers tell the browser or client what happened with the request and provide extra information.
import { Controller, Get, Res, HttpStatus } from '@nestjs/common'; import { Response } from 'express'; @Controller('example') export class ExampleController { @Get() exampleMethod(@Res() res: Response) { res.status(HttpStatus.OK).set('Custom-Header', 'value').send('Hello'); } }
Use @Res() to get the response object and control status and headers.
HttpStatus provides easy-to-read status code names.
res.status(200).send('OK');
res.status(HttpStatus.NOT_FOUND).send('Not Found');res.set('X-Custom-Header', '123').send('With header');
res.status(302).set('Location', '/new-url').send();
This controller has three routes:
/status/success sends a 200 status with a custom header and message./status/error sends a 400 status with an error header and message./status/redirect sends a 302 redirect to the success route.import { Controller, Get, Res, HttpStatus } from '@nestjs/common'; import { Response } from 'express'; @Controller('status') export class StatusController { @Get('success') success(@Res() res: Response) { res.status(HttpStatus.OK).set('X-Message', 'Success').send('Request succeeded'); } @Get('error') error(@Res() res: Response) { res.status(HttpStatus.BAD_REQUEST).set('X-Error', 'Invalid data').send('Bad request'); } @Get('redirect') redirect(@Res() res: Response) { res.status(HttpStatus.FOUND).set('Location', '/status/success').send(); } }
Using @Res() means you handle the response fully; NestJS won't send it automatically.
Always set status before sending the response.
Headers must be set before sending the body.
Status codes tell the client what happened with the request.
Headers provide extra information about the response.
In NestJS, use @Res() with Express response to set status and headers.
201 usually indicate in a response?X-Custom-Header with value 123 in a NestJS controller using Express response?res.set() to set headers.res.set() accepts header name and string value. res.set('X-Custom-Header', '123'); uses correct method and string value.async getData(@Res() res) {
res.status(204).set('X-Info', 'No Content').send();
}async update(@Res() res) {
res.status(200);
res.set('Content-Type', 'application/json');
res.send({ success: true });
res.status(201);
}X-Request-ID and a JSON body in NestJS. Which code snippet correctly achieves this?Pass the test and this pattern moves unknown