question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

req.body empty in NestMiddleware

See original GitHub issue

Bug Report

Current behavior

Currently based on the process of bodyParser and middleware, I must create one which will be body/headers related to handle further request to the database (e.g. based on request select specific DB, not hard coded) everything been working till I figured that the req.body is empty in this context so I used raw-body instead, but while doing it, it happen that body is purged somewhere in process and it is not assigned to next function.

So 2 questions there:

  1. How to enable req.body in Middleware? Currently req.body always returns undefined while data is placed. If I get this right Middleware can be used to tuning the request a bit, before it is sent to the controllers and validations etc.
  2. How come body is purged in process of using simple Middleware with raw-body?

Input Code

My main.ts:

    app.useGlobalFilters(new QueryFailedErrorFilter());
    app.useGlobalPipes(
        new ValidationPipe({
            whitelist: true
        }),
    );
    app.use(new MyMiddleware().use);

My MyMiddleware (regarding question 1.):

import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class MyMiddleware implements NestMiddleware {
    use(req, res, next: Function) {
            req.body is always undefined
}

My MyMiddleware (regarding question 2.):

import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class MyMiddleware implements NestMiddleware {
    async use(req, res, next: Function) {
            if (req.url === '/login' && req.method === 'POST') {
                const body = await rawbody(req);
                const bodyJSON = JSON.parse(body.toString());
                const bodyJsonMail = bodyJSON.mail;
                ...
            }
           next();
}

Expected behavior

I would like to operate body in Middleware (get one value from it) and then have use of ValidationPipe for further validation of given bodies.

Environment


Nest version: 6.8.1
 
For Tooling issues:
- Node version: 10.15.3
- Platform:  Windows

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
kamilmysliwieccommented, Oct 11, 2019

Your middleware is applied before bodyParser. Instead of using app.use(), you should rather follow this example: https://docs.nestjs.com/middleware#applying-middleware, so in your case:

 consumer
      .apply(MyMiddleware)
      .forRoutes('*');
1reaction
kamilmysliwieccommented, Oct 10, 2019

Please, provide a minimal repository which reproduces your issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

NestJS req.body from POST method is empty/undefined when ...
Solution: request.body is undefined is: NestJS use as default body jsonBody, so in that case you have to override for specific routes that...
Read more >
why is req.body undefined | The Search Engine You Control
If you don't have any such middleware, then req.body will be empty and the body of the request will remain in the incoming...
Read more >
How to parse the raw body of a request in a nest js controller
In my application I return the entity model directly for GET requests and I like having arrays as empty instead of undefined properties....
Read more >
Why my request.body is empty while request.params in not?
Hi guys,. I have this simple express code which prints the request.body. But it's empty. When I print request.query then I get some...
Read more >
Full-stack app tutorial with NestJS and React - LogRocket Blog
In this code, we use the @Res() decorator to send a response to the client, and the @Body() decorator to parse the data...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found