前端如何自己写接口? - Nest篇

演示环境

Node:20.11.1

Npm:10.5.0

Nest:10.3.2

前言

1、写这篇文章前,我也去了解了其他类似的框架、网友的评价、框架的优缺点...等等等等

2、总结来说:Nest适合前端 去了解、学习,对前端友好,性能说得过去,没有太多额外的学习成本,开发效率高

3、对于后端来说,适合了解一下;虽然现在NodeJs工程师也有招聘,但如果真正想学后端,还是建议学主流的后端语言,比如go、python、java...等

开始

NestJs中文文档 - 点击进入

1、全局安装Nest:npm i -g @nestjs/cli
2、创建项目:nest new 项目名称

创建完成后,结构如下:

3、用VsCode打开,运行项目,也可以用命令:npm run start

4、运行完毕后,浏览器访问:http://localhost:3000/

整理目录

删减、整理完毕后,结构如下:

启动类(main.ts)添加:启动成功后的信息

ts 复制代码
import { NestFactory } from '@nestjs/core';
import { AppModule } from './module/app.module';
import { Logger } from '@nestjs/common';

async function bootstrap() {
  // 创建日志对象,参数名称自定义,也可以是类名,我这里就用 Application
  const logger = new Logger('Application');

  const app = await NestFactory.create(AppModule);
  await app.listen(3000, () => {
    // 项目启动成功后的回调函数
    // 打印启动成功后的信息
    logger.log('项目启动成功,访问地址: http://localhost:3000');
  });
}
bootstrap();

效果:

初始化数据库

MySQL:8.0.36(我的版本)
1、新建一个数据库,我这里命名为:db2

2、创建一个表:student(学生表),结构如下:

3、使用客户端生成一些测试数据

各字段生成规则:

测试数据生成结果:

ps:使用工具的好处就省去了人力,节省时间,不用自己一个个去手动创建测试数据

Nest配置数据源

ps:Nest提供了现成的ORM:TypeORM,当然也有其他的ORM,感兴趣的可以去了解一下

1、下载 TypeORM:npm install --save @nestjs/typeorm typeorm mysql2
2、数据库配置:app.module.ts

ts 复制代码
import { Module } from '@nestjs/common';
import { AppController } from '../controller/app.controller';
import { AppService } from '../service/app.service';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    // 应用数据库配置
    TypeOrmModule.forRoot({
      // 数据库类型
      type: 'mysql',
      // 主机地址
      host: 'localhost',
      // 数据库端口
      port: 3306,
      // 用户名
      username: 'root',
      // 密码
      password: '123456',
      // 连接的数据库
      database: 'db2',
      // 实体类自动扫描
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      // 重连次数
      retryAttempts: 10,
      // 重连间隔
      retryDelay: 3000,
      // 开启日志
      logging: true,
      extra: {
        // 连接池配置
        connectionLimit: 10, // 连接池最大连接数
        pollPingInterval: 60, // 连接间隔,60秒
        pollTimeout: 60, // 连接超时时间,60秒
      },
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

3、如果配置无误,项目就能启动成功;若启动失败,检查配置是否正确

编写Mapper层 - SQL执行层

Mapper层相当于SpringBoot内的同名层,也叫Dao层,Nest内也可以写在Service层,但博主习惯用这层来存放SQL执行函数

资料:TypeORM中文文档 - 点击进入
1、在 mapper 目录下创建 student.mapper.ts 文件

ps:TypeORM提供了一些内置函数,博主只是习惯写SQL语句,这个查询方式不一定跟我的一样

ts 复制代码
import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';

/**
 * 学生Mapper类
 */

@Injectable()
export class StudentMapper {
  // 数据源依赖注入
  constructor(private datasource: DataSource) {}
  // 学生表名
  private readonly studentTName = 'student';

  /**
   * 查询所有学生信息
   *
   * @returns 学生信息集合
   */
  async findAll(): Promise<any> {
    // 执行查询语句 - 异步函数
    const stutents = await this.datasource.query(
      `SELECT * FROM ${this.studentTName}`,
    );
    // 返回查询到的结果
    return stutents;
  }
}

编写 Service 层 - 业务逻辑层

在 service 目录下创建 stutent.service.ts 文件

ts 复制代码
import { Injectable } from '@nestjs/common';
import { StudentMapper } from 'src/mapper/student.mapper';

/**
 * 学生业务实现类
 */

@Injectable()
export class StudentService {
  // 学生数据源依赖注入
  constructor(private studentMapper: StudentMapper) {}

  /**
   * 查询所有学生信息
   *
   * @returns 返回的结果
   */
  async queryAllStudent(): Promise<any> {
    return {
      code: 200,
      success: true,
      data: await this.studentMapper.findAll(),
    };
  }
}

编写 Controller 层 - 控制器层

在 controller 目录下创建 stutent.controller.ts 文件

ts 复制代码
import { Controller, Get } from '@nestjs/common';
import { StudentService } from 'src/service/stutent.service';

/**
 * 学生控制器
 */

@Controller('Student')
export class StudentController {
  // 学生业务类依赖注入
  constructor(private readonly studentService: StudentService) {}

  @Get('queryAllStudent')
  async queryAllStudent(): Promise<any> {
    return this.studentService.queryAllStudent();
  }
}

编写 Module 层 - 模块层

在 module 目录下创建 stutent.module.ts 文件

ts 复制代码
import { Module } from '@nestjs/common';
import { StudentController } from 'src/controller/student.controller';
import { StudentMapper } from 'src/mapper/student.mapper';
import { StudentService } from 'src/service/stutent.service';

/**
 * 学生模块
 */

@Module({
  providers: [StudentMapper, StudentService],
  controllers: [StudentController],
})
export class StudentModule {}

导入学生模块至根模块

在 app.module.ts 的 imports 中导入 StudentModule 模块

启动项目,测试接口

1、启动项目,浏览器访问:http://localhost:3000/Student/queryAllStudent

ps:调用成功则会返回所有的学生信息,至此你已经完成了一个简单的查询接口

前端调用

1、vite.config.ts 中配置一下接口请求路径和跨域

ps:不配置会出现跨域问题,这里跨域建议在后端、Nginx配置,实在不了解前两者结合实际情况才在前端配置跨域,后面详细介绍Nest配置时我会教大家配置跨域

2、封装api

ps:博主个人以前喜欢直接在页面Method的函数中直接调用Send,但是为了规范,还是封装一下

3、创建测试页面,调用接口测试

ts 复制代码
<template>
    <div class="body">
        <div>
            {{ title }}
        </div>
        <div>
            <el-button @click="queryAll">获取所有学生信息</el-button>
        </div>
        <div>
            <pre ref="stuList"></pre>
        </div>
    </div>
</template>

<script lang="ts">
import { QueryAllStudent } from '@/api/test';
import { defineComponent } from 'vue';

export default defineComponent({
    name: 'Index',
    data() {
        return {
            title: 'Nest接口测试'
        };
    },
    computed: {},
    mounted() {},
    methods: {
        queryAll() {
            QueryAllStudent((data: any) => {
                console.log('接口返回的数据:{}', data);
                let stuList = this.$refs.stuList as HTMLElement;
                stuList.innerHTML = JSON.stringify(data, null, 2);
            });
        }
    },
    created() {},
    onBeforeUnmount() {}
});
</script>

<style lang="scss" scoped></style>

测试效果:

至此,你已经初步入门NestJS了

结语

希望对你能有所帮助,有问题可以私信或下方留言给我

相关推荐
会编程的吕洞宾4 分钟前
Spring Cloud Gateway 限流鉴权与灰度发布实战
java·经验分享·后端·spring
BingoGo5 分钟前
Laravel FFmpeg9 发布了!用全新 API 处理视频编码与 HLS、DASH 流媒体
后端·php
JaguarJack12 分钟前
Laravel FFmpeg9 发布了!用全新 API 处理视频编码与 HLS、DASH 流媒体
后端·php·laravel
学长毕设39 分钟前
基于SpringBoot 宠物商城领养网站-附源码
spring boot·后端·宠物
AAA修煤气灶刘哥1 小时前
AI 写的 SQL 跑通了,为什么和财务报表对不上?
人工智能·后端·算法
Rain的Java大神之路2 小时前
别再背概念了:中台不是大数仓,湖仓一体也不是“湖+仓”——从电商下单链路一次讲透数据库、数仓、数据湖、中台、湖仓一体
大数据·数据库·后端
程序员cxuan2 小时前
这 6 个 Gemini 命令,真给我用爽了
人工智能·后端·程序员
FYKJ_201012 小时前
springboot众创项目团队管理系统94666-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·spark·课程设计
码事漫谈13 小时前
AI出来四年了
后端
CoderYanger13 小时前
Java EE 进阶:14.案例综合练习-博客系统(第二弹):博客详情+令牌技术
服务器·前端·spring boot·后端·spring·java-ee·github