NestJs中的各种请求与携带参数的解析
demo.controller.ts
import { Body, Param, Controller, Delete, Get, Post, Patch } from '@nestjs/common' ;
import { DemoService } from './demo.service' ;
import { adduser, updateuser } from "./types/index"
@ Controller ( 'demo' )
export class DemoController { constructor ( private demoService: DemoService) { } @ Get ( "/getuserlist" ) getUserlist ( ) { return this . demoService. getUserlist ( ) } @ Get ( "/getuserlist/:name" ) getUserlistParam ( @ Param ( 'name' ) name: string ) { return this . demoService. getUserlistParam ( name) } @ Post ( "/adduser" ) createUser ( @ Body ( ) userdata: adduser) { return this . demoService. addUser ( userdata. name) } @ Delete ( "/deleteuser" ) deleteUser ( @ Body ( ) name: adduser) { return this . demoService. deleteUser ( name. name) } @ Delete ( "/deleteuser/:name" ) deleteUserParam ( @ Param ( 'name' ) name: string ) { return this . demoService. deleteUserParam ( name) ; } @ Patch ( "/updateuser" ) updateUser ( @ Body ( ) userdata: updateuser) { return this . demoService. updateUser ( userdata. NewName, userdata. OldName) }
}
demo.service.ts
import { Injectable } from '@nestjs/common' ;
@ Injectable ( )
export class DemoService { getUserlist ( ) { return [ "John" , "Jane" , "Bob" ] ; } getUserlistParam ( username: string ) { return ` User ${ username} found ` ; } addUser ( user: string ) { return ` User ${ user} added successfully ` ; } deleteUser ( user: string ) { return ` User ${ user} deleted successfully ` ; } updateUser ( user: string , newUser: string ) { return ` User ${ user} updated to ${ newUser} successfully ` ; } deleteUserParam ( username: string ) { return ` User ${ username} deleted successfully ` ; }
}