简体   繁体   中英

@Get('*') doesn't match empty (NestJS)

Within my Nest backend I'm trying to match a url within my controller

@Controller('admin')
export class AdminController {
    @Get('*') 
    getAdminB(@Res() response): void {
        response.sendFile(path.resolve('./public/admin/index.html'));
    }
}

This should match the following URLS:

/admin
/admin/
/admin/anything

However, the above get @Get('*') doesn't match /admin . Should I add an other route with @Get() or is there a fix for this?

I need this because I have to serve an angular app from /admin

You can use the path @Get('/?*') to match all routes.

Why does this work?

Nest uses the util function validatePath() to build the path. When you have a prefix ( admin in your case), then nest will always add a / between the prefix and the path from your route decorator unless the first char is already a / .

export const validatePath = (path?: string): string =>
  path
    ? path.charAt(0) !== '/' ? '/' + path : path
    : '';

So the path that is given to express will be admin/?* which matches any path that starts with admin . Careful , this also includes eg adminarea/1 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM