likes
comments
collection
share

NestJS博客实战01-NestJS基本功能介绍

作者站长头像
站长
· 阅读数 46
by 雪隐 from https://juejin.cn/user/1433418895994094
本文欢迎分享与聚合,全文转载就不必了,尊重版权,圈子就这么大,若急用可联系授权

大家好我是雪隐,请叫我雪宝,一个走了很长弯路的前端工程师。这一章就超级简单的介绍下,NestJS的基本功能,为之后的开发做准备。还有实际的项目可能不是按照顺序来说明的,希望大家看一下Nest基本概念

Nest CLI 介绍

在开始写后端代码之前,先简单介绍下几个比较实用的CLI命令,以后可能会经常的用到。不做详细说明,有兴趣的话,大家可以去官网查看说明。

  1. 通过help可以查看全部命令的使用方法。
nest --help

NestJS博客实战01-NestJS基本功能介绍

可以看到全部的命令并不是很多,new,build,start,info,add,generate,竖线后面的是它的简写。其中generate或者g会被经常的使用。

### 经常会使用的nest Cli 命令 ###

# 创建一个新的项目,执行完命令以后。
nest new project-name

# 打包和运行项目,一般使用npm命令这里不做介绍
# 。。。。

## 生成常用的三件套
nest g mo cats
nest g co cats
nest g s cats

## 生成一个Nest元素 ##
# 创建一个Class
nest generate class myClass .
nest g cl myClass .

# 创建一个拦截器
nest generate interceptor myInterceptor .
nest g inc myInterceptor 
  1. 通过help查看generate命令的使用方法
nest generate --help
# 或者
nest g --help

NestJS博客实战01-NestJS基本功能介绍

Nest 各个模块简单介绍

  1. Nest的基本构造
  • app.controller.spec.ts -> controller测试文件
  • app.controller.ts -> 一个基本的Controller
  • app.module.ts -> 应用程序的根模块
  • app.service.ts -> 基本的服务service
  • main.ts -> 项目的端点,服务启动,全局拦截器,过滤器等,第三方中间件等。
  1. Nest的基本要素

原则上是这3个组合成一个机能。

  • Module
  • Controller
  • Service

2-1. Module

  • 把相关联的ControllerService整合起来注册到NestJS中。
  • NestJS应用程序至少要有一个根路由。

2-2. Controller

  • 接受从客户端来的请求,并且返回处理后的结果。
  • Controller可以指定特定的路径(列: /usersUsersController绑定)
  • Controller内定义的方法可以指定HTTP方法和请求路径。

2-3. Service(Hello world)

  • 写实现业务逻辑的代码
  1. 管道

  2. 其他(守卫,拦截器)

创建一个项目 并 跑起来

我们项目的结构如下: NestJS博客实战01-NestJS基本功能介绍

一些工具,调试功能的配置

  • 接下来我们来试着创建一个最基础的项目。选择用pnpm做安装依赖。然后等待完成就行了。
nest n juejin-shenblog

NestJS博客实战01-NestJS基本功能介绍

  • vsCode配置debug
  1. 点击调试按钮 NestJS博客实战01-NestJS基本功能介绍

  2. 创建launch.json文件,调试器选择Node.js NestJS博客实战01-NestJS基本功能介绍

  3. 修改launch.json代码

{
  "version": "0.2.0",
  "configurations": [
    {
      // 调试的类型
      "type": "node",
      // 调试的方式分为 launch 和 attach 2种,因为package已经有了debug方法,我们只要attach到9229端口就行了
      "request": "attach",
      // 自定义名字
      "name": "Attach NestJS WS",
      // attach 对应的端口
      "port": 9229,
      // 发生变更时是否重启
      "restart": true
    }
  ]
}
  1. 启动项目并且点击调试按钮

通过下面的命令来启动项目,并确认是否监听9229端口

npm run start:debug

NestJS博客实战01-NestJS基本功能介绍

点击调试

NestJS博客实战01-NestJS基本功能介绍

打个短点,然后访问网页试试,如果可以调试配置就没问题了

NestJS博客实战01-NestJS基本功能介绍

本章代码

代码

转载自:https://juejin.cn/post/7211284290066890808
评论
请登录