Issue
My @Body() in my NestJS App seems always to be undefined. I dont use any middleware right now, so I am quite confused how this can happen. Here is my setup:
Controller:
import { Body, Controller, HttpCode, HttpStatus, Post, Req } from "@nestjs/common";
import { AuthService } from './auth.service';
@Controller('api/auth')
export class AuthController {
constructor(private authService: AuthService) {}
@HttpCode(HttpStatus.OK)
@Post('login')
signIn(@Body() signInDto: Record<string, any>) {
return this.authService.signIn(signInDto.username, signInDto.password);
}
}
Here the signInDto is always undefined. Also if I pass the @Req() to the function, it is also undefined..
main.ts:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { tenancyMiddleware } from './modules/tenancy/tenancy.middleware';
import { DataSource, getConnection, getManager } from 'typeorm';
import { getTenantConnection } from './modules/tenancy/tenancy.utils';
import { SnakeNamingStrategy } from './snake-naming.strategy';
import { join } from 'path';
import { appDataSource } from './datasource.app';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// config
const configService = app.get(ConfigService);
const port = configService.get<number>('port');
app.enableCors();
// Multitenancy
//app.use(tenancyMiddleware);
await appDataSource.initialize();
await appDataSource.runMigrations();
const schemas = await appDataSource.query(
'select schema_name as name from information_schema.schemata;',
);
for (let i = 0; i < schemas.length; i += 1) {
const { name: schema } = schemas[i];
if (schema.startsWith('tenant_')) {
const tenantId = schema.replace('tenant_', '');
const connection = await getTenantConnection(tenantId);
await connection.runMigrations();
await connection.close();
}
}
await app.listen(port);
}
bootstrap();
Postman Headers:
{
"accept": "application/json",
"content-type": "application/json",
"user-agent": "PostmanRuntime/7.36.1",
"cache-control": "no-cache",
"host": "localhost:3000",
"accept-encoding": "gzip, deflate, br",
"connection": "keep-alive",
"content-length": "28"
}
All I found from other questions was to add the content-type header, but it did not fix it. Any hints why my body is always undefined?
Solution
This is a recent "bug" on using multiple versions of reflect-metadata
in the project, as discussed here: https://github.com/nestjs/nest/issues/13107
Downgrading typeorm
package to 0.3.19
instead of using 0.3.20
, should fix that for now.
Answered By - Micael Levi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.