使用NestJS开发安全API:创建端点 - Auth0

作者:API传播员 · 2026-01-16 · 阅读时间:5分钟
本教程详细指导如何使用NestJS框架创建安全的API端点,通过构建菜单管理系统实现CRUD操作,包括定义端点、创建控制器、处理HTTP请求以及启用数据验证,帮助开发者构建健壮的后端服务。

使用NestJS开发安全API:创建端点

在本教程中,我们将学习如何使用NestJS创建安全的API端点。通过构建一个简单的菜单管理系统,您将了解如何定义端点、创建控制器、数据验证。


克隆项目并设置环境

首先,克隆应用程序仓库并切换到“创建数据模型和服务”分支:

git clone git@github.com:auth0-blog/wab-menu-api-nestjs.git 
nest-restaurant-api 
--branch creating-data-models-and-service

将项目文件夹设置为当前目录,然后安装项目依赖项:

npm install

接着,创建一个.env文件,并根据需要填充环境变量。


定义API端点

本应用程序的目标是创建以下端点来管理菜单项的CRUD操作:

  • GET /items: 获取所有项目(公共端点)
  • GET /items/:id: 根据ID获取单个项目
  • POST /items: 创建新项目
  • PUT /items: 更新现有项目
  • DELETE /items/:id: 根据ID删除项目

我们将从公共的“GET”端点开始实现。


创建NestJS控制器

要创建“Items Controller”,运行以下命令:

nest generate controller items --no-spec

此命令会在src/items目录下生成一个items.controller.ts文件,并自动将其注册到Items Module中:

// src/items/items.module.ts
import { Module } from '@nestjs/common';
import { ItemsService } from './items.service';
import { ItemsController } from './items.controller';

@Module({
  providers: [ItemsService],
  controllers: [ItemsController],
})
export class ItemsModule {}

在NestJS中,控制器负责将HTTP请求映射到特定功能。控制器通过类和装饰器定义,例如:

@Controller('items')
export class ItemsController {}

实现端点

src/items/items.controller.ts中实现所有端点:

import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
import { ItemsService } from './items.service';
import { Items } from '../items';
import { Item } from '../item';

@Controller('items')
export class ItemsController {
  constructor(private readonly itemsService: ItemsService) {}  @Get()
  async findAll(): Promise {
    return this.itemsService.findAll();
  }  @Get(':id')
  async find(@Param('id') id: number): Promise {
    return this.itemsService.find(id);
  }  @Post()
  async create(@Body('item') item: Item): Promise {
    this.itemsService.create(item);
  }  @Put()
  async update(@Body('item') item: Item): Promise {
    this.itemsService.update(item);
  }  @Delete(':id')
  async delete(@Param('id') id: number): Promise {
    this.itemsService.delete(id);
  }
}

关键点解析

  1. 路由路径:所有端点共享items/路径,定义在@Controller装饰器中。
  2. 路由处理程序:每个HTTP请求类型(如GETPOST)对应一个方法,使用装饰器(如@Get@Post)标记。
  3. 异步处理:由于数据提取通常是异步的,方法使用async并返回Promise
  4. 服务注入:通过构造函数注入ItemsService,将业务逻辑委托给服务层。

测试API请求

启动开发服务器:

npm run start:dev

测试获取所有项目的端点:

curl http://localhost:7000/items/

测试创建新项目的端点:

curl -X POST -H 'Content-Type: application/json' 
-d '{ "item": { "name": "Salad", "price": 4.99, "description": "Fresh", "image": "https://cdn.auth0.com/blog/whatabyte/salad-sm.png" } }' 
http://localhost:7000/items -i

验证项目是否成功添加:

curl http://localhost:7000/items -i

启用数据验证

在生产环境中,API可能会接收到不可预测的请求有效载荷。为确保数据有效性,我们可以使用NestJS的内置验证管道。

安装验证依赖

npm install class-validator class-transformer

配置全局验证管道

更新src/main.ts文件:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();

添加验证规则

src/item.ts中定义验证规则:

import { IsString, IsNumber, IsOptional } from 'class-validator';

export class Item {
  @IsNumber()
  @IsOptional()
  readonly id: number;  @IsString()
  readonly name: string;  @IsNumber()
  readonly price: number;  @IsString()
  readonly description: string;  @IsString()
  readonly image: string;
}

测试验证

发送无效的POST请求:

curl -X POST -H 'Content-Type: application/json' 
-d '{ "item": { "name": 1.99, "price": "Salad", "description": "Fresh", "image": "https://cdn.auth0.com/blog/whatabyte/salad-sm.png" } }' 
http://localhost:7000/items -i

响应将返回400 Bad Request,并包含详细的错误信息。


总结

通过本教程,您学习了如何使用NestJS创建安全的API端点,包括定义路由、实现控制器、处理请求以及启用数据验证。这些步骤为构建健壮的后端服务奠定了基础。下一步,您可以继续扩展功能或优化现有代码。

原文链接: https://auth0.com/blog/developing-a-secure-api-with-nestjs-creating-endpoints/