Search code examples
nestjsbody-parserreq

Accept form-data in Nest.js


I have written auth routes in Nestjs and wanted to use it with the form-data. I got it working with URL-encoded-form-data, JSON, text, but not receiving anything in the body when I use form-data and really want it to work with form-data as on the front-end I am hitting the route with form-data. I have tried every way I could find on the web, but none of them helped me in this case. so after hours of searching and trying when I didn't get any lead I am posting my question here. Any Kind of Help is appreciated.

Code of signup endpoint:

@Post('native/loginWithPhone')
async loginWithPhoneNative(@Body() { phone }: LoginWithPhoneDto) {
    return await this.securityCodeService.sendSecurityCodeNative(phone, 'otp');
}

@Post('signup')
async signup(@Request() req, @Body() body) {
    console.log(req)
    console.log(body)
    return await req.body
    // return await this.authService.signupWithEmail({
    //   email,
    //   password,
    //   dob,
    //   role: process.env.ROLE_USER,
    // });
}

Main.ts configurations :

import * as bodyParser from 'body-parser'
import * as multer from 'multer';
global. fetch = require('node-fetch');

async function bootstrap() {
    require('dotenv').config();

    const app = await NestFactory.create(AppModule, {
    bodyParser: true,
});

await app.init();
app.enableCors();

app.use(multer)
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.text({type: 'text/html'}))
app.use(bodyParser.json())
app.useGlobalPipes(new ValidationPipe());

empty body I am getting on postman empty body I am getting on postman


Solution

  • NestJS provides a built-in multipart/form-data parser which you can access using a FileInterceptor.

    Here's an example of how you'd read a single file (as you've shown in your screenshot):

    @Post('signup')
    @UseInterceptors(FileInterceptor('<name of file here - asdasd in your screenshot>'))
    signup(@UploadedFile() file, @Body() body) {
      console.log(file);
      console.log(body);
    }