我開始學習 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;
}
}
正如您在代碼中看到的,我正在嘗試檢索名稱引數。但是當我在瀏覽器中訪問此 URL http://localhost:3000/?name=test 時,我收到以下錯誤。
http://localhost:3000/?name=test
當我轉而訪問這個 URL 時,http://localhost:3000/test,它只是繼續加載頁面。我的代碼有什么問題,我該如何解決?
uj5u.com熱心網友回復:
有兩種型別的引數裝飾器。
@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;
}
- 在客戶端上查詢引數
@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;
}
使用郵遞員localhost:3000/john?age=30您可以@Query從@Param
另請注意,@Query如果您不使用請求 DTO,則使用數字 if 將始終被決議為字串
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436469.html
