Nest框架快速上手
介绍
Nest 是一个用于构建高效,可扩展的 Node.js 服务器端应用程序的框架。它使用渐进式 JavaScript,内置并完全支持 TypeScript(但仍然允许开发人员使用纯 JavaScript 编写代码)并结合了 OOP(面向对象编程),FP(函数式编程)和 FRP(函数式响应编程)的元素。
在底层,Nest 使用强大的 HTTP Server 框架,如 Express(默认)和 Fastify。Nest 在这些框架之上提供了一定程度的抽象,同时也将其 API 直接暴露给开发人员。这样可以轻松使用每个平台的无数第三方模块。
安装
npm i -g @nestjs/cli
nest new project-name
启动项目
yarn start:dev
访问默认的地址 http://localhost:3000
我们找到 src\app.service.ts 文件,修改一下代码
import {
Injectable } from '@nestjs/common'
@Injectable()
export class AppService {
getHello(): string {
return 'Hello Nest!'
}
}
然后刷新地址,可以看到返回值已经改变了
修改默认端口
方式一:
找到 main.ts 文件,直接修改默认的启动端口,如图
方式二:
通过配置文件的方式来修改
安装
yanr add @nestjs/config
然后修改 app.module.ts 文件
import {
Module } from '@nestjs/common'
import {
AppController } from './app.controller'
import {
AppService } from './app.service'
import {
ConfigModule } from '@nestjs/config'
@Module({
imports: [
// 配置模块,用于读取配置文件
ConfigModule.forRoot({
isGlobal: true // 全局可用
})
],
controllers: [AppController],
providers: [AppService]
})
export class AppModule {
}
接着在根目录新建 .env 文件
PORT=3003
重启项目,此时的默认端口就变成了3003
创建question模块和路由
在项目目录下依次执行如下命令
nest g module question
nest g controller question --no-spec
nest g service question --no-spec
--no-spec
的意思是不要生成测试文件
执行完毕后,可以看到自动生成了这三个文件
然后 app.module.ts 中也自动帮我们引入了 QuestionModule
import {
Module } from '@nestjs/common'
import {
AppController } from './app.controller'
import {
AppService } from './app.service'
import {
ConfigModule } from '@nestjs/config'
import {
QuestionModule } from './question/question.module'
@Module({
imports: [
// 配置模块,用于读取配置文件
ConfigModule.forRoot({
isGlobal: true // 全局可用
}),
QuestionModule
],
controllers: [AppController],
providers: [AppService]
})
export class AppModule {
}
接下来我们来创建一个 question/list 接口
先在 question.service.ts 文件中新增一个 findAll 方法,模拟返回一些数据
import {
Injectable } from '@nestjs/common'
@Injectable()
export class QuestionService {
findAll() {
return [
{
id: 1,
title: '输入框',
type: 'QuestionInput',
props: {
text: '姓名',
placeholder: '请输入姓名'
}
}
]
}
}
然后在 question.controller.ts 文件中引入 service 并定义 get 请求,返回 findAll 方法的返回值
import {
Controller, Get } from '@nestjs/common'
import {
QuestionService } from './question.service'
@Controller('question')
export class QuestionController {
constructor(private readonly questionService: QuestionService) {
}
@Get('findAll')
findAll() {
return this.questionService.findAll()
}
}
做完这些后,来访问一下这个接口 http://localhost:3003/question/findAll
可以看到,已经正常返回了
获取请求参数
Param路径参数
question.controller.ts 文件新增接口
@Get('getQuestionInfo/:id')
getQuestionInfo(@Param('id') id: string) {
console.log('路径参数:', id)
return id
}
接口格式:question/getQuestionInfo/123
Query路由参数
@Get('getQuestionList')
getQuestionList(
@Query('pageNum') pageNum: number,
@Query('pageSize') pageSize: number
) {
console.log('pageNum:', pageNum)
console.log('pageSize', pageSize)
return {
pageNum,
pageSize
}
}
接口格式:question/getQuestionList?pageNum=1&pageSize=10
Body请求体参数
首先定义DTO,新建 src\question\dto\Question.ts
export class Question {
readonly title: string
readonly type: string
}
然后定义接口
@Post('updateQuestion')
updateQuestion(@Body() question: Question) {
console.log('body参数' + JSON.stringify(question))
return question
}
接口格式:POST /question/updateQuestion
连接Mongodb数据库
首先需要安装所需依赖
yarn add @nestjs/mongoose mongoose
然后在 AppModule 中引入 MongooseModule
import {
Module } from '@nestjs/common'
import {
AppController } from './app.controller'
import {
AppService } from './app.service'
import {
ConfigModule } from '@nestjs/config'
import {
QuestionModule } from './question/question.module'
import {
MongooseModule } from '@nestjs/mongoose'
@Module({
imports: [
// 配置模块,用于读取配置文件
ConfigModule.forRoot({
isGlobal: true // 全局可用
}