Nest: [NestMiddleware][Request, Respon] Request param is empty

Created on 3 Mar 2020  路  6Comments  路  Source: nestjs/nest

Bug Report

Params from a request like this: /api/project/sdadasda is empty

Current behavior


I'm creating a middleware and using NestMiddleware, i would like to get params from my request but it always empty

Input Code

// Controller


@Controller('/api/project')
export class ProjectController {
  constructor(private projectService: ProjectService) {}

  @Get(':id')
  public findOne(@Param('id') id: string) {
    return ['this.projectService.findOne(id)']
  }
}
// Middleware

import {
  HttpException,
  Injectable,
  Logger,
  NestMiddleware,
} from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as HttpStatus from 'http-status';
import { AuthService } from './auth.service';


@Injectable()
export class AuthMiddleware implements NestMiddleware<Request, Response> {
  constructor(private readonly authService: AuthService) {}

  public async use(req: Request, res: Response, next: NextFunction) {
    const token = {
      idToken: req.header('Authorization'),
    };

    console.log('Request Params', req.params)

    const decodedToken = await this.authService.verifyToken(token);

    if (decodedToken.code) {
      throw new HttpException(
        {
          status: HttpStatus.INTERNAL_SERVER_ERROR,
          error: decodedToken.code,
          message: decodedToken.message,
          data: [],
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    } else {
      // console.log(res)
      next();
    }
  }
}

Expected behavior


i would like to get params from my request

Possible Solution

Environment


Nest version:6.7.2


For Tooling issues:
- Node version: 12 
- Platform: Linux  

Others:

needs clarification

Most helpful comment

@baotd86
When I make a request with an id abcd it works as expected. The Nest middleware has nothing to do with the empty route parameter. req.params will return parameters in the matched route.

Please make sure double check if you set the configure() method of the module class correctly.

@Controller('auth')
export class AuthController {
  @Get(':id')
  public findOne(@Param('id') id: string) {
    console.log(id); // abcd
  }
}

// Correct
@Module({
  controllers: [AuthController]
})
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes({ path: "*", method: RequestMethod.ALL });
  }
}

// Correct
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes(AuthController);
  }
}

// Also works
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes({ path: 'auth/:id', method: RequestMethod.ALL });
  }
}

// req.params will be an empty object
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes('auth');
  }
}

// Not work
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes({ path: 'auth', method: RequestMethod.ALL });
  }
}

All 6 comments

Please, provide a minimal repository which reproduces your issue.

@baotd86

Can you try to import Request and Response from express and see if this changes anything?

Please, provide a minimal repository which reproduces your issue.

Sorry for my mistake,
I'm using Request, Response classes from express
import { Request, Response, NextFunction } from 'express';

@baotd86

Can you try to import Request and Response from express and see if this changes anything?

Yep, I did but the issue still there

@baotd86
When I make a request with an id abcd it works as expected. The Nest middleware has nothing to do with the empty route parameter. req.params will return parameters in the matched route.

Please make sure double check if you set the configure() method of the module class correctly.

@Controller('auth')
export class AuthController {
  @Get(':id')
  public findOne(@Param('id') id: string) {
    console.log(id); // abcd
  }
}

// Correct
@Module({
  controllers: [AuthController]
})
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes({ path: "*", method: RequestMethod.ALL });
  }
}

// Correct
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes(AuthController);
  }
}

// Also works
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes({ path: 'auth/:id', method: RequestMethod.ALL });
  }
}

// req.params will be an empty object
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes('auth');
  }
}

// Not work
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes({ path: 'auth', method: RequestMethod.ALL });
  }
}
Please make sure double check if you set the configure() method of the module class correctly.

Oh, i got it. thank you very much for your guide. It's work for me now

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FranciZ picture FranciZ  路  3Comments

mishelashala picture mishelashala  路  3Comments

rafal-rudnicki picture rafal-rudnicki  路  3Comments

JulianBiermann picture JulianBiermann  路  3Comments

KamGor picture KamGor  路  3Comments