nestjs从0开始学

189 阅读1分钟

nestjs官网: nestjs.com/
nestjs中文网(个人常用):NestJS 中文网
nestjs中文网: 第一步

第一步:

npm i -g @nestjs/cli
nest new project-name
cd new project-name
npm run start

访问http://localhost:3000/,可以看到Hello World!

控制器

控制器负责处理传入请求向客户端返回响应

image.png

参数获取

param: restful api 参数 ,常用于get

// localhost/data/1
@Get('/data/:id')
getData(@Param() params){
 console.log(params);// 打印{id:1}
 console.log(params.id);// 打印1
}

body: post参数

@Post('/data')
getData(@Body() body){
 console.log(body);
}

query: url参数,主要是?id=1这种

// localhost/data?id=1
@Post('/data')
getData(@Body() body,@query() query){
 console.log(query.id);//打印1
}

快速生成

nest g resource user
nest g controller user
nest g module user

运行

npm run start
npm run start:dev // 开发过程中会监听代码变化,热更新