」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 掌握 NestJS 中的資料驗證:類別驗證器和類別轉換器的完整指南

掌握 NestJS 中的資料驗證:類別驗證器和類別轉換器的完整指南

發佈於2024-11-08
瀏覽:101

Introduction

In the fast-paced world of development, data integrity and reliability are paramount. Robust data validation and efficient handling of user data can make the difference between a smooth experience and an inconsistent application state.

George Fuechsel’s quote below summarizes what this article is about.

“Garbage in, garbage out.” — George Fuechsel

In this article, we will dive into data validation in NestJS. We will explore some complex use cases of class-validator and class-transformer to ensure data are valid and properly formatted. Along the way, we will discuss best practices, some advanced techniques, and common pitfalls to take your skills to the next level. My motive is to equip you to build more resilient and error-proof applications with NestJS.

Whiles we go through this journey together, keep in mind that we should never trust any inputs submitted by a user or client external to the application, regardless of whether it is part of a larger service(micro-service).

Table Of Contents

  • Introduction
  • Data Transfer Object (DTO). What is it?
  • Initial Configuration: Setting Up Your NestJS Project
  • Creating User DTOs
  • Adding Class Validators to Fields
  • Validating Nested Objects
  • Using Transform() and Type() from Class-transformer
  • Conditional Validation
  • Handling Validation Errors
  • Understanding Pipes
  • Setting Up a Global Validation Pipe
  • Formatting Validation Errors
  • Creating Custom Validators
  • Custom Password Validator
  • Asynchronous Custom Validator With Custom Validation Options
  • Common Pitfalls and Best Practices
  • Conclusion
  • Additional Resources

Data Transfer Object (DTO). What is it?

DTO is a pattern we can leverage to encapsulate data and transfer it to different layers of the application. They are useful for managing the data that flows in(request) and out(response) of the app.

Immutable DTOs

As we have already established, the main idea for using DTOs is to transfer data and as such, the data should not be changed after they have been created. In general, DTOs are designed to be immutable, meaning that once they are created their properties can not be modified. Some benefit that comes with this include but not limited to:

  • Predictable behavior: The confidence that its data remains unchanged.
  • Consistency: Once it is created, its state remains unchanged throughout its lifecycle until it’s garbage collected.

JavaScript does not have a built-in type for creating immutable types like we have record types in Java and C#. We can achieve similar behavior by making our fields readonly.

Initial Configuration: Setting Up Your NestJS Project

We will start with a mini user management project, which will include basic CRUD operations to manage users. If you’d like to explore the full source code, you can click here to access the project on GitHub.

Install NestJS CLI

$ npm i -g @nestjs/cli  
$ nest new user-mgt

Install class-validator and class-transformer

npm i --save class-validator class-transformer

Generate the user module

$ nest g resource users  
? What transport layer do you use? REST API  
? Would you like to generate CRUD entry points? No

Create an empty DTO and entities folder. After everything, you should have this structure.

Mastering Data Validation in NestJS: A Complete Guide with Class-Validator and Class-Transformer

Creating User DTOs

Let’s begin by creating the necessary DTOs. This tutorial will focus on only two actions, creating and updating a user. Create two files in the DTO folder

user-create.dto.ts

export class UserCreateDto {  
  public readonly name: string;  
  public readonly email: string;  
  public readonly password: string;  
  public readonly age: number;  
  public readonly dateOfBirth: Date;  
  public readonly photos: string[];  
}  

user-update.dto.ts

import { PartialType } from '@nestjs/mapped-types';  
import { UserCreateDto } from './user-create.dto';  

export class UserUpdateDto extends PartialType(UserCreateDto) {}

UserUpdateDto extends UserCreateDto to inherit all properties, the PartialType ensures that all fields are optional allowing for partial update. This saves us time so we don’t have to repeat it.

Adding Class Validators to Fields

Let’s break down how to add validation to the fields. Class-validator provides us with a lot of already-made validation decorators to which we can apply these rules to our DTOs. For now, we will use a few to validate UserCreateDto. click here for the full list.

import {  
  IsString,  
  IsEmail,  
  IsInt,  
  Min,  
  Max,  
  Length,  
  IsDate,  
  IsArray,  
  ArrayNotEmpty,  
  ValidateNested,  
  IsUrl,  
} from 'class-validator';  
import { Transform, Type } from 'class-transformer';  

export class UserCreateDto {  
  @IsString()  
  @Length(2, 30, { message: 'Name must be between 2 and 30 characters' })  
  @Transform(({ value }) => value.trim())  
  public readonly name: string;  

  @IsEmail({}, { message: 'Invalid email address' })  
  public readonly email: string;  

  @IsString()  
  @Length(8, 50, { message: 'Password must be between 8 and 50 characters' })  
  public readonly password: string;  

  @IsInt()  
  @Min(18, { message: 'Age must be at least 18' })  
  @Max(100, { message: 'Age must not exceed 100' })  
  public readonly age: number;  

  @IsDate({ message: 'Invalid date format' })  
  @Type(() => Date)  
  public readonly dateOfBirth: Date;  

  @IsArray()  
  @ValidateNested()  
  @ArrayNotEmpty({ message: 'Photos array should not be empty' })  
  @IsString({ each: true, message: 'Each photo URL must be a string' })  
  @IsUrl({}, { each: true, message: 'Each photo must be a valid URL' })  
  public readonly photos: string[];  
}

Our simple class has grown in size, we have annotated the fields with decorators from Class-Validator. These decorators apply validation rules to the fields. You may have questions about the decorators if you are new to this. For example, what do they mean? Let’s break down some of the basic validators we have used.

  • IsString() → This decorator ensures that a value is a string.
  • Length(min, max) → This ensures that the string has a link within the specified range.
  • IsInt() → This decorator checks if the value is an integer.
  • Min() and Max() → This ensures that a numeric value falls between the range
  • IsDate() → This ensures that the value is a valid date
  • IsArray() → Validates that the value is an array
  • IsUrl() → Validate the value is a valid URL
  • Transform() → Change the data into a different format

Decorator Parameters

The UserCreateDto fields validator contains additional properties passed into it. These allow you to:

  • Customize validation rules
  • Provide values
  • Set validation options
  • Provide messages when the validation fails etc.

Validating Nested Objects

Unlike normal fields validating nested objects requires a bit of extra processing, class-transformer together with class-validator allows you to validate nested objects.

We did a little bit of nested validation in UserCreateDto when we validated the photos field.

@IsArray()  
@IsUrl({}, { each: true, message: 'Each photo must be a valid URL' })  
public readonly photos: string[];

Photos are an array of strings. To validate the nested strings, we added ValidateNested() and { each: true } to ensure that, each link is a valid URL.

Let’s update photos a some-what complex structure. create a new file in DTO folder and name it user-photo.dto.ts

import { IsString, IsInt, Min, Max, IsUrl, Length } from 'class-validator';  

export class UserPhotoDto {  
  @IsString()  
  @Length(2, 100, { message: 'Name must be between 2 and 100 characters' })  
  public readonly name: string;  

  @IsInt()  
  @Min(1, { message: 'Size must be at least 1 byte' })  
  @Max(5_000_000, { message: 'Size must not exceed 5MB' })  
  public readonly size: number;  

  @IsUrl(  
    { protocols: ['http', 'https'], require_protocol: true },  
    { message: 'Invalid URL format' },  
  )  
  public readonly url: string;  
}

Now let’s update the photos section of UserCreateDto

export class UserCreateDto {  
  // Other fields  

  @IsArray()  
  @ArrayNotEmpty({ message: 'Photos array should not be empty' })  
  @ValidateNested({ each: true })  
  @Type(() => UserPhotoDto)  
  public readonly photos: UserPhotoDto[];  
}

The ValidateNested() decorator ensures that each element in the array is a valid photo object. The most important thing to be aware of when it comes to nested validation is that the nested object must be an instance of a class else ValidateNested() won’t know the target class for validation. This is where class-transformer comes in.

Using Transform() and Type() from Class-transformer

Class-transformer provides us with the @Type() decorator. Since Typescript doesn’t have good reflection capabilities yet, we use @Type(() => UserPhotoDto) to give an instance of the class.

We can also utilize the Type() decorator for basic data transformation in our DTO. The dateOfBirth field in UserCreateDto is transformed into a date object using @Type(() => Date).

For complex DTO fields transformation, the Tranform() decorator handles this perfectly. It allows you to access both the field value and the entire object being validated. Whether you’re converting data types, formatting strings, or applying custom logic, @Transform() gives you the control to return the exact version of the value that your application needs.

  @Transform(({ value, obj }) => {  
    // perform additional transformation  
    return value;  
  })

Conditional Validation

Most often, some fields need to be validated based on some business rules, we can use the ValidateIf() decorator, which allows you to apply validation to a field only if some condition is true. This is very useful if a field depends on other fields like multi-step forms.

Let’s update the UserPhotoDto to include an optional description field, which should only be validated if it is provided. If the description is present, it should be a string with a length between 10 and 200 characters.

export class UserPhotoDto {  
  // Other fields  

  @ValidateIf((o) => o.description !== undefined)  
  @IsString({ message: 'Description must be a string' })  
  @Length(10, 200, {  
    message: 'Description must be between 10 and 200 characters',  
  })  
  public readonly description?: string;  
}

Handling Validation Errors

Before we dive into how NestJS handles validation errors, let’s first create simple handlers in the user.controller.ts. We need a basic route to handle user creation.

import { Body, Controller, Post } from '@nestjs/common';  
import { UserCreateDto } from './dto/user-create.dto';  

@Controller('users')  
export class UsersController {  
  @Post()  
  createUser(@Body() userCreateDto: UserCreateDto) {  
    // delegating the creation to a service  
    return {  
      message: 'User created successfully!',  
      user: userCreateDto,  
    };  
  }  
}

Trying this endpoint on Postman with no payload gives us a successful response.

Mastering Data Validation in NestJS: A Complete Guide with Class-Validator and Class-Transformer

Mastering Data Validation in NestJS: A Complete Guide with Class-Validator and Class-Transformer

NestJS has a good integration with class-validator for data validation. Still, why wasn’t our request validated? To tell NestJS that we want to validate UserCreateDto we have to supply a pipe to the Body() decorator.

Understanding Pipes

Pipes are flexible and powerful ways to transform and validate incoming data. Pipes are any class decorated with Injectable() and implement the PipeTransform interface. The usage of pipe we are interested is its ability to check that an incoming request meets a certain criteria or throw errors if otherwise.

The most common way to validate the UserCreateDto is to use the built-in ValidationPipe. This pipe validates rules in your DTO defined with class-validator

Now we pass a validation pipe to the Body() to validate the DTO

import { Body, Controller, Post, ValidationPipe } from '@nestjs/common';  
import { UserCreateDto } from './dto/user-create.dto';  

@Controller('users')  
export class UsersController {  
  @Post()  
  createUser(@Body(new ValidationPipe()) userCreateDto: UserCreateDto) {  
    // delegating the creation to services  
    return {  
      message: 'User created successfully!',  
      user: userCreateDto,  
    };  
  }  
}

With this small change, we get the errors below if we try to create a user with no payload.

Mastering Data Validation in NestJS: A Complete Guide with Class-Validator and Class-Transformer

Awesome right :)

Setting Up a Global Validation Pipe

To ensure that all requests are validated across the entire application. We have to set up a global validation pipe so that we don’t have to pass validation pipe to every Body() decorator.

Update 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({  
      whitelist: true,  
      transform: true,  
    }),  
  );  
  await app.listen(3000);  
}  

bootstrap();

The built-in validation pipe uses class-transformer and class-validator, we can pass validations options to be used by these underlying packages. whitelist: true automatically strips any properties that are not defined in the DTO.transform: true automatically transforms the payload into the appropriate types defined in your DTO.

ValidationPipe({  
   whitelist: true,  
   transform: true,  
}),

With this, we can remove the pipe we passed to createUser endpoint and it will still be validated. Passing it to parameters helps us fine-tune the validation we need for specific endpoints.

@Post()  
createUser(@Body() userCreateDto: UserCreateDto) {  
  // ...  
}

Formatting Validation Errors

The default validation errors format is not bad, we get to see all the errors for the validations that failed, Some frontend developers will scream at you though for mixing all the errors, I have been there?. Another reason to separate it is when you want to display errors under the fields that failed on the UI.

For nested objects, we also need to retrieve all the errors recursively for a smooth experience. We can achieve this by passing a custom exceptionFactory method to format the errors.

Update main.ts

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      exceptionFactory: (validationErrors: ValidationError[] = []) => {
        const getPrettyClassValidatorErrors = (
          validationErrors: ValidationError[],
          parentProperty = '',
        ): Array => {
          const errors = [];

          const getValidationErrorsRecursively = (
            validationErrors: ValidationError[],
            parentProperty = '',
          ) => {
            for (const error of validationErrors) {
              const propertyPath = parentProperty
                ? `${parentProperty}.${error.property}`
                : error.property;

              if (error.constraints) {
                errors.push({
                  property: propertyPath,
                  errors: Object.values(error.constraints),
                });
              }

              if (error.children?.length) {
                getValidationErrorsRecursively(error.children, propertyPath);
              }
            }
          };

          getValidationErrorsRecursively(validationErrors, parentProperty);

          return errors;
        };

        const errors = getPrettyClassValidatorErrors(validationErrors);

        return new BadRequestException({
          message: 'validation error',
          errors: errors,
        });
      },
    }),
  );
  await app.listen(3000);
}

bootstrap();

Mastering Data Validation in NestJS: A Complete Guide with Class-Validator and Class-Transformer

This looks way better. Hopefully, you don’t go through what I went through with the front-end developers to get here ?. Let’s go through what is happening.

We passed an anonymous function to exceptionFactory. The functions accept the array of validation errors. Diving into the validationError interface.

export interface ValidationError {  
    target?: Record;  
    property: string;  
    value?: any;  
    constraints?: {  
        [type: string]: string;  
    };  
    children?: ValidationError[];  
    contexts?: {  
        [type: string]: any;  
    };  
}

For example, if we apply IsEmail() on a field and the provided value is not valid. A validation error is created. We also want to know the property where the error occurred. We need to keep in mind that, we can have nested objects for example the photos in UserCreateDto and therefore we can have a parent property let’s say, photos where the error is with the url in the UserPhotoDto.

We first declare an inner function, that takes the errors and sets the parent property to an empty string since it is the root field.

const getValidationErrorsRecursively = (
  validationErrors: ValidationError[],
  parentProperty = '',
) => {

};

We then loop through the errors and get the property. For nested objects, I prefer to show the fields as photos.0.url. Where 0 is the index of the invalid photo in the array.

Mastering Data Validation in NestJS: A Complete Guide with Class-Validator and Class-Transformer

The error messages are stored in the constraints field as it’s in the validationError interface. We retrieve these errors and store them under a specific field.

if (error.constraints) {  
  errors.push({  
    property: propertyPath,  
    errors: Object.values(error.constraints),  
  });  
}

For nested objects, the children property of a validation error contains an array of validationError for the nested objects. We can easily get the errors by recursively calling our function and passing the parent property.

if (error.children?.length) {  
  getValidationErrorsRecursively(error.children, propertyPath);  
}

Creating Custom Validators

While Class-validator provides a comprehensive set of built-in validators, there are times when your requirements exceed the standard validation rules or the standard validation doesn’t fit what you want to do. Custom validators are useful when you need to enforce rules that aren’t covered by the standard validators. Examples:

  • We can create a custom validator to enforce a specific rule on what a valid password should be.
  • We can create another to ensure that the username is unique.

To create a custom validator, we have to define a new class that implements the ValidatorConstraintInterface from class-validator. This requires us to implement two methods:

  • validate → Contains your validation logic and must return a boolean
  • defaultMessage → Optional default message to return when the validation fails.

Custom Password Validator

Create a new folder in users module named validators. Create two files, is-valid-password.validator.ts and is-username-unique.validator.ts. It should look like this.

Mastering Data Validation in NestJS: A Complete Guide with Class-Validator and Class-Transformer

A valid password in our use case is very simple. it should contains

  • At least one uppercase letter.
  • At least one lowercase letter.
  • At least one symbol.
  • At least one number.
  • Password length should be more than 5 characters and less than 20 characters.

Update is-valid-password.validator.ts

import {  
  ValidatorConstraint,  
  ValidatorConstraintInterface,  
  ValidationArguments,  
} from 'class-validator';  

@ValidatorConstraint({ name: 'IsStrongPassword', async: false })  
export class IsValidPasswordConstraint implements ValidatorConstraintInterface {  
  validate(password: string, args: ValidationArguments) {  
    return (  
      typeof password === 'string' &&  
      password.length > 5 &&  
      password.length ]/.test(password)  
    );  
  }  

  defaultMessage(args: ValidationArguments) {  
    return 'Password must be between 6 and 20 characters long and include at least one uppercase letter, one lowercase letter, one number, and one special character';  
  }  
}

IsValidPasswordContraint is a custom validator because it is decorated with ValidatorConstraint(), we provide our custom validation rules in the validate method. If the validate function returns false, the error message in the defaultMessage will be returned. Providing these methods implements the ValidatorContraintInterface. To use isValidPasswordContraint, update the password field in UserCreateDto. For ValidatorConstraint({ name: ‘IsStrongPassword’, async: false }), we provided the constraint name that will be used to retrieve the error and also, since all actions in the validate are synchronous, we set async to false.

import { Validate } from 'class-validator';  

export class UserCreateDto {  
  // other fields  

  @Validate(IsValidPasswordConstraint)  
  public readonly password: string;  
}

Now, if we try again with an invalid password, we get this result indicating our custom validator is working.

Mastering Data Validation in NestJS: A Complete Guide with Class-Validator and Class-Transformer

We can go further and create a decorator for the validator so that we can decorate the password field without using the Validate.

Update is-valid-password.validator.ts

import {  
  ValidatorConstraint,  
  ValidatorConstraintInterface,  
  ValidationArguments,  
  registerDecorator,  
  ValidatorOptions,  
} from 'class-validator';  

@ValidatorConstraint({ name: 'IsStrongPassword', async: false })  
class IsValidPasswordConstraint implements ValidatorConstraintInterface {  
  // removing the implementation so that we focus on IsPasswordValid function  
}  

export function IsValidPassword(validationOptions?: ValidatorOptions) {  
  return function (object: NonNullable, propertyName: string) {  
    registerDecorator({  
      target: object.constructor,  
      propertyName: propertyName,  
      options: validationOptions,  
      constraints: [],  
      validator: IsValidPasswordConstraint,  
    });  
  };  
}

Creating custom decorators makes working with validators a breeze, NestJs gives us registerDecorator to create our own. we provide it with the validator which is the IsValidPasswordContraint we created. We can use it like this

export class UserCreateDto {  
  // other fields    

  @IsValidPassword()  
  public readonly password: string;  
}

Asynchronous Custom Validator With Custom Validation Options

It is common to encounter scenarios where you need to validate against external systems. Let’s assume that the username in UserCreateDto is unique across the various servers.

Update is-unique-username.validator.ts

import {  
  ValidatorConstraint,  
  ValidatorConstraintInterface,  
  ValidationArguments,  
  registerDecorator,  
  ValidationOptions,  
} from 'class-validator';  

interface IsUsernameUniqueOptions {  
  server: string;  
  message?: string;  
}  

@ValidatorConstraint({ name: 'IsUsernameUnique', async: true })  
export class IsUsernameUniqueConstraint  
  implements ValidatorConstraintInterface  
{  
  async validate(username: string, args: ValidationArguments) {  
    const options = args.constraints[0] as IsUsernameUniqueOptions;  
    const server = options.server;  

    // server check, let assume username exist  
    return !(await this.checkUsernameOnServer(username, server));  
  }  

  defaultMessage(args: ValidationArguments) {  
    const options = args?.constraints[0] as IsUsernameUniqueOptions;  
    return options?.message || 'Username is already taken';  
  }  

  async checkUsernameOnServer(username: string, server: string) {  
    return true;  
  }  
}  

export function IsUsernameUnique(  options: IsUsernameUniqueOptions,  
  validationOptions?: ValidationOptions,) {  
  return function (object: object, propertyName: string) {  
    registerDecorator({  
      target: object.constructor,  
      propertyName: propertyName,  
      options: validationOptions,  
      constraints: [options],  
      validator: IsUsernameUniqueConstraint,  
    });  
  };  
}

Usage

export class UserCreateDto {  
  @IsString()  
  @Length(2, 30, { message: 'Name must be between 2 and 30 characters' })  
  @Transform(({ value }) => value.trim())  
  @IsUsernameUnique({ server: 'east-1', message: 'Name already exists' })  
  public readonly name: string;  

  // other fields  
}

We created a simple interface to show the possible options we can pass to the decorator. These options are constraints that will be used by IsUsernameUniqueConstraint, we can get them through the validation arguments . const options = args.constraints[0] as IsUsernameUniqueOptions;

Logging options give us { server: ‘east-1’, message: ‘Name already exists’ }, We then called the required service and passed the server name and username to validate the uniqueness of the name.

Also, async is set to true to allow asynchronous operations inside the validate function; ValidatorConstraint({ name: ‘IsUsernameUnique’, async: true }).

Common Pitfalls and Best Practices

It is necessary to be aware of common pitfalls to ensure robust and maintainable code.

  • Avoid direct use of entities. One common mistake is using entities directly. Entities are typically used for database interactions and may contain fields or relationships that shouldn’t be exposed or validated on incoming requests.
  • Test Custom Validators Extensively. Validation logic is a critical part of your application’s security and data integrity. Ensure they are well-tested.
  • Be Explicit with Error Messages. Provide error messages that are informative and user-friendly. It should communicate what the user should do to correct it.
  • Leverage Built-in and Custom Validators Together. Our IsUniqueUsername validator still uses IsString() on the name field. We don’t have to reinvent everything if it is already available.

Conclusion

There is so much to add like validation groups, using service containers, etc, but this article is getting way longer than I anticipated ?. As you continue developing with NestJS, I encourage you to explore more complex use cases and scenarios and share your experiences to keep the learning journey going.

Data validation is crucial in ensuring data integrity within any application and the principles covered here will serve as a strong foundation for further growth and mastery in building secure and efficient applications.

This is my very first article, and I’m eager to hear your thoughts! ? Please feel free to leave any feedback in the comments.

If you’d like to connect and stay updated on future content, you can find me on LinkedIn

Happy Coding !!!

Additional Resources

  • https://github.com/typestack/class-validator?tab=readme-ov-file#class-validator
  • https://github.com/typestack/class-transformer?tab=readme-ov-file#what-is-class-transformer
  • https://docs.nestjs.com/pipes
  • https://docs.nestjs.com/techniques/validation
版本聲明 本文轉載於:https://dev.to/ahurein/mastering-data-validation-in-nestjs-a-complete-guide-with-class-validator-and-class-transformer-40fj?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • JavaScript 中基本物件和函數連結的原則是什麼?
    JavaScript 中基本物件和函數連結的原則是什麼?
    了解 JavaScript 中的基本物件/函數鏈函數鍊是一種程式設計技術,可讓開發人員建立按特定順序執行的操作序列。在 JavaScript 中,這是透過傳回函數本身和使用 this 關鍵字結合來實現的。 要了解連結的原理,讓我們來看一個工作範例:var one = function(num) { ...
    程式設計 發佈於2024-11-08
  • 開發工具不是必需的
    開發工具不是必需的
    幾個月前我正在開發一個前端專案。該專案是一個微前端,旨在整合到遺留儀表板上。 採用微前端方法的原因是為了降低儀表板上的複雜度。我對這個挑戰感到興奮並投入其中。 我使用 webpack、react 和 typescript 設定微前端。我使用 chakra ui 作為 CSS-IN-JS 框架,使...
    程式設計 發佈於2024-11-08
  • OpenAI 在簡化程式碼方面出奇地好
    OpenAI 在簡化程式碼方面出奇地好
    While browsing the Internet for inspiration, I came across an interesting-looking component. I thought the block with the running ASCII art looked coo...
    程式設計 發佈於2024-11-08
  • 有毒的 Laravel 社區如何摧毀了我對程式設計的熱情。
    有毒的 Laravel 社區如何摧毀了我對程式設計的熱情。
    我仍然记得那件事就像昨天一样,但当我踏上成为一名 Web 开发人员的旅程时,已经是二十多年前了。 我拨打了我的 56k 调制解调器,占用了电话线,这样我就可以浏览一些我最喜欢的网站。然后我想知道如何自己制作。 我发现我可以在 Microsoft Word 中处理 HTML。我创建了一个包含滚动字幕、...
    程式設計 發佈於2024-11-08
  • 與工人一起部署
    與工人一起部署
    按鈕產生器 按鈕產生器是一款旨在簡化 GitHub 上託管專案的部署流程的工具。透過建立「部署到 Cloudflare Workers」按鈕,您可以簡化部署流程,讓使用者只需按一下即可將您的應用程式部署到 Cloudflare Workers。 此按鈕為使用者提供了一種將專案直接...
    程式設計 發佈於2024-11-08
  • 使用 PHP 操作字串
    使用 PHP 操作字串
    字串是程式設計中用來表示字元序列的資料型別。這些字元可以是字母、數字、空格、符號等。在許多程式語言中,字串用單引號 (') 或雙引號 (") 括起來。 字串連線 連接是將兩個或多個字串連接在一起的過程。 <?php $name = "John"; $lastname = "...
    程式設計 發佈於2024-11-08
  • jQuery 可以幫助使用 Comet 模式進行伺服器傳送訊息嗎?
    jQuery 可以幫助使用 Comet 模式進行伺服器傳送訊息嗎?
    利用Comet 透過jQuery 進行伺服器傳送訊息在JavaScript 程式設計領域,伺服器推播功能已經獲得了突出地位,彗星設計模式正在成為一種流行的方法。本文探討了建構在著名 jQuery 函式庫之上的此類解決方案的可用性。 基於 jQuery 的 Comet 實現儘管 Comet 模式很流行...
    程式設計 發佈於2024-11-08
  • 如何在 Keras 中實作 Dice 誤差係數的自訂損失函數?
    如何在 Keras 中實作 Dice 誤差係數的自訂損失函數?
    Keras 中的自訂損失函數:實作Dice 誤差係數在本文中,我們將探討如何建立自訂損失函數在Keras 中,聚焦在Dice 誤差係數。我們將學習實現參數化係數並將其包裝以與 Keras 的要求相容。 實現係數我們的自訂損失函數將需要係數和一個包裝函數。此係數測量 Dice 誤差,該誤差比較目標值和...
    程式設計 發佈於2024-11-08
  • 為什麼 MySQL 會拋出「警告:mysql_fetch_assoc 參數無效」錯誤?
    為什麼 MySQL 會拋出「警告:mysql_fetch_assoc 參數無效」錯誤?
    MySQL 警告:mysql_fetch_assoc 的參數無效問題:嘗試從MySQL 檢索資料時資料庫時,遇到以下錯誤訊息:mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource說明:mysql_fet...
    程式設計 發佈於2024-11-08
  • 在 Python 中使用 ElementTree 的「find」和「findall」方法時如何忽略 XML 命名空間?
    在 Python 中使用 ElementTree 的「find」和「findall」方法時如何忽略 XML 命名空間?
    在ElementTree 的“find”和“findall”方法中忽略XML 命名空間使用ElementTree 模組解析和定位XML 文件中的元素時,命名空間會帶來複雜性。以下介紹如何在 Python 中使用「find」和「findall」方法時忽略命名空間。 當 XML 文件包含命名空間時,會導...
    程式設計 發佈於2024-11-08
  • 為什麼在 Node.js 應用程式中連接到 MySQL 時出現「connect ECONNREFUSED」錯誤?
    為什麼在 Node.js 應用程式中連接到 MySQL 時出現「connect ECONNREFUSED」錯誤?
    Node.js MySQL:解決「connect ECONNREFUSED」錯誤將Node.js 應用程式部署到遠端伺服器時,您可以嘗試建立與MySQL 資料庫的連線時遇到「connect ECONNREFUSED」錯誤。當 MySQL 連線參數中提供的主機配置不正確時,通常會出現此問題。 在您的特...
    程式設計 發佈於2024-11-08
  • 用 Go 建構密碼管理器
    用 Go 建構密碼管理器
    作为一名软件开发人员,我一直对安全性和可用性的交集着迷。最近,我决定开始一个令人兴奋的项目:使用 Go 创建一个命令行密码管理器。我想与您分享这段旅程的开始,从第一次提交开始。 创世记 2023 年 11 月 27 日,我对我的项目进行了初步提交,我将其命名为“dost”(印地语中的...
    程式設計 發佈於2024-11-08
  • 如何使用 HTML ruby​​ 元素在 HTML 中增強文字註釋
    如何使用 HTML ruby​​ 元素在 HTML 中增強文字註釋
    在本教程中,我們將探索如何有效地使用 HTML 元素來建立增強的文字註解。 HTML5 中的 元素旨在顯示 ruby​​ 註釋,這是東亞排版中常用的小文字元件。這些註釋通常用於提供發音指南或附加資訊。 元素對於需要在正文旁邊或上方進行詳細註釋的文檔至關重要,這使其在教育內容、語言學習資源和某...
    程式設計 發佈於2024-11-08
  • 如何使用 RequestAnimationFrame 來穩定動畫的幀速率 (FPS)?
    如何使用 RequestAnimationFrame 來穩定動畫的幀速率 (FPS)?
    RequestAnimationFrame Fps 穩定RequestAnimationFrame (rAF) 已在動畫中變得流行,可提供流暢且高效的執行。然而,控制幀速率 (FPS) 以確保一致性可能具有挑戰性。 將 rAF 限制為特定 FPS要將 rAF 限制為特定 FPS,您可以自上一幀執行以...
    程式設計 發佈於2024-11-08
  • 如何實作跨域JavaScript的JSONP回呼?
    如何實作跨域JavaScript的JSONP回呼?
    跨域JavaScript的JSONP回調實現為了方便不同域之間的通信,引入了JSONP(JSON with Padding)。此技術涉及建立一個回調函數,該函數可用於包裝 JSON 資料並使其可以從不同的網域進行存取。以下是如何在PHP 中實作JSONP:接受回呼參數首先,在GET 請求中,我們接受...
    程式設計 發佈於2024-11-08

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3