Nest.js 路由参数没有返回任何内容

Wai*_*ein 0 node.js nestjs

我开始学习 Nest.js。现在我想了解路由参数是如何工作的。

我有一个带有以下代码的控制器。

import {Controller, Get, Param, Req, Res} from '@nestjs/common';
import { AppService } from './app.service';
import {Request, Response} from "express";

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get(':name')
  getHello(@Param('name') name: string,
           @Req() req: Request,
           @Res() res: Response): string {
    return name;
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您在代码中看到的,我正在尝试检索名称参数。但是当我在浏览器中访问此 URL http://localhost:3000/?name=test 时,出现以下错误。

http://localhost:3000/?name=test
Run Code Online (Sandbox Code Playgroud)

当我访问此 URL http://localhost:3000/test 时,它只会继续加载页面。我的代码有什么问题以及如何修复它?

You*_*gla 6

有 2 种类型的 params 装饰器。

  • @Param('name') param: string 您使用的客户端上的路由参数http://localhost:3000/:name 您将获得name字符串形式

使用邮递员http://localhost:3000/john

  @Get(':name')
  getHello(@Param('name') name: string,
           @Req() req: Request,
           @Res() res: Response): string {
    return name;
  }
Run Code Online (Sandbox Code Playgroud)
  • @Query() query: {[key: string]: string} 您使用的客户端上的查询http://localhost:3000/?name=test&age=40 参数得到的对象是 {name: "test",age: "40"}

使用两者的示例

 @Get(':name')
  getHello(@Param('name') name: string,
           @Query() query: {age: string}
           @Req() req: Request,
           @Res() res: Response): string {
    return name;
  }
Run Code Online (Sandbox Code Playgroud)

使用邮递员localhost:3000/john?age=30您可以从 访问年龄@Query并从 访问姓名@Param

@Query另请注意,如果不使用请求 DTO,则使用数字将始终被解析为字符串