Consider this NestJS controller method:
@Post('create')
create(@Body() data: any) {
return { received: data.name };
}If you send a POST request to /create with JSON body {"name": "Alice"}, what will be the response?
import { Controller, Post, Body } from '@nestjs/common'; @Controller() export class AppController { @Post('create') create(@Body() data: any) { return { received: data.name }; } }
Think about how NestJS parses JSON request bodies automatically.
The @Body() decorator extracts the parsed JSON body as an object. So data.name accesses the name property, returning "Alice".
Given this NestJS controller method:
@Post('user')
createUser(@Body() body: any) {
const city = ???;
return city;
}The request body JSON is {"user": {"address": {"city": "Paris"}}}. Which code correctly assigns city to "Paris"?
import { Controller, Post, Body } from '@nestjs/common'; @Controller() export class AppController { @Post('user') createUser(@Body() body: any) { const city = ???; return city; } }
Follow the JSON structure step by step.
The JSON has user at top level, then address, then city. So body.user.address.city accesses "Paris".
Look at this controller method:
@Post('data')
receiveData(@Body('info') info: string) {
return info;
}A client sends JSON {"user": {"info": "hello"}} but the method returns undefined. Why?
import { Controller, Post, Body } from '@nestjs/common'; @Controller() export class AppController { @Post('data') receiveData(@Body('info') info: string) { return info; } }
Check the JSON structure and what @Body('info') expects.
The @Body('info') decorator extracts the 'info' property from the root of the JSON body. If the client sends JSON with 'info' nested inside another object, it returns undefined.
Given this method:
@Post('update')
update(@Body() body: { id: number; name?: string }) {
return { id: body.id, name: body.name ?? 'Unknown' };
}If the client sends {"id": 5} (no name), what is the response?
import { Controller, Post, Body } from '@nestjs/common'; @Controller() export class AppController { @Post('update') update(@Body() body: { id: number; name?: string }) { return { id: body.id, name: body.name ?? 'Unknown' }; } }
Look at the nullish coalescing operator ??.
If body.name is missing or undefined, ?? 'Unknown' sets the name to "Unknown".
Choose the correct statement about how NestJS handles request bodies.
Think about how HTTP headers affect body parsing.
By default, NestJS uses body-parser middleware that parses JSON only when Content-Type is 'application/json'. Other types need extra setup.