Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Nest.js framework in node

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian for you to introduce in detail "how to use the Nest.js framework in node", the content is detailed, the steps are clear, the details are handled properly, I hope that this article "how to use the Nest.js framework in node" can help you solve your doubts, the following follows the editor's ideas slowly in depth, together to learn new knowledge.

Brief introduction of Nest.js Framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, built-in and fully supports TypeScript (but still allows developers to write code in pure JavaScript) and combines elements of OOP (object-oriented programming), FP (functional programming) and FRP (functional response programming).

The underlying HTTP platform of the Nest framework is implemented based on Express by default, so there is no need to worry about the lack of third-party libraries. Nest aims to be a platform-independent framework. Through the platform, you can create reusable logical components that developers can use to span many different types of applications. Nest currently has two HTTP platforms that support out-of-the-box support: express and fastify can be introduced directly into the project.

Why choose Nest?

At present, there are many node frameworks on the market to choose from.

Express.js is the beginning of Node.JS. It is a fast and minimalist JS server development framework based on Node.js and Chrome V8 engine.

Koa.js is a miniature Web framework, it is easy to write a hello world, but web applications can not do without session, view templates, routing, file upload, log management. These Koa are not provided, so you need to go to the official Middleware to find them. However, 100 people may find 100 combinations.

Egg.js is based on Koa.js, solves the above problems, integrates community best practices into Koa.js, also known as Egg.js, and solves problems such as multi-process startup and hot updates during development. This is developer-friendly, right out of the box, and out of the box is the best configuration. During the development of Egg.js, ECMAScript introduced async await, which is more straightforward than yield's syntax async. Later, Koa.js also followed up synchronously.

Midway is a Node.js framework developed by Ali team based on progressive concept, which combines two programming paradigms: OOP and functional. With egg as the underlying framework and many new features such as good TypeScript definition support, Midway has been launched. Interested partners can go to the official documentation to learn.

Nest.js is based on Express.js 's full-function framework Nest.js, which is encapsulated on Express.js and makes full use of the characteristics of TypeScript; the advantage of Nest.js is that the community is active and the rise is gratifying. Up to now, 43.7k Star is a popular enterprise framework in GitHub.

Based on the comprehensive consideration of supporting the underlying support of ts and enterprise and community activity, I choose to use nest to learn here. Students can choose according to their needs.

Create a project

Make sure the computer has Node.js installed (> = 10.13.0)

The node version I use here is v14.16.1 and the yarn managed version is 1.22.17.

Create a project

$npm I-g @ nestjs/cli$ nest new project-name

After creating the project, take a look at the project directory. Here is a brief description of the core file:

App.controller.ts sample basic controller with a single route app.controller.spec.ts unit tests the root module of the sample app.module.ts application for the basic controller. App.service.ts has a basic service main.ts application entry file with a single method. Used to create Nest application instances. / * main.ts * / import {NestFactory} from'@ nestjs/core';import {AppModule} from'. / app.module';async function bootstrap () {const app = await NestFactory.create (AppModule); / / return an interface object await app.listen (3000) using the core class NestFactory; / / here is the default port number} bootstrap ()

Run the project

$npm run start:watch / / start the project and listen for code changes here you can configure instructions in package.json

We can see that the service has been started. Enter the local address with the port number 3000. If you send a get request, you will return `Hello World`. This is because the @ Get () HTTP request decorator in the app.controll.ts file tells Nest to create a handler for the specific endpoint of the HTTP request. Routin

Before we start writing code, let's take a brief look at the basic routing configuration in nest. For now, my understanding is that the routing of nest is provided to the front end by a route map composed of a global routing prefix (local routing) method decorator.

In the / * main.ts * / main file, we can configure a global api prefix async function bootstrap () {const app = await NestFactory.create (AppModule); / / set the global prefix app.setGlobalPrefix ('api'); await app.listen (3000) before project monitoring } / * app.controller.ts * / @ Controller ('user') / / Controller sets routing prefix I understand as local route export class AppController {constructor (private readonly appService: AppService) {} @ Get (' find') / / method decorator sets routing path here I understand it as setting API child route getHello (): string {return this.appService.getHello ();}}

The above method maps to a complete route as GET api/user/find in api.

Where the @ Get () HTTP request decorator tells Nest to create a handler for the specific endpoint of the HTTP request.

You can see that the above get receives requests and routes so that they can be used. Let's take a look at how to receive post and other request methods in nest.

Receive requests in different ways

The request decorator knowledge point Request object provided by Nest used here represents the HTTP request and has the properties of the query string, request parameters, HTTP header (HTTP header) and body (HTTP body) (read more here). In most cases, you don't have to get them manually. We can use specialized decorators, such as @ Body () or @ Query (), which are used out of the box. The following is a comparative list of the decorators provided by Nest and the underlying platform-specific objects they represent.

Let's take a look at how to receive requests initiated by get post put delete in nest, using several available decorators to create a basic controller. The controller exposes several ways to access and manipulate internal data.

Get

Let's first create a user service / controller / moudle

/ * user.service.ts * / first create a user service service file import {Injectable} from'@ nestjs/common'; @ Injectable () / here export class UserService {findUser (sid: string): string {console.log (sid); if (sid = = '123456') {return' kid is here';} return'No one here';}}

The service, which will be responsible for data storage and retrieval, is used by UserController, and we decorate this class with @ Injectable ()

/ * user.controller.ts * / create a user controller file import {Controller, Get, Query} from'@ nestjs/common';import {UserService} from'. / user.service';@Controller ('user') export class UserController {constructor (private readonly userService: UserService) {} @ Get (' findOne') / / the route exposed here is user/find findUser (@ Query () query: any) {return this.userService.findUser (query.sid);}

The purpose of the controller is to receive specific requests from the application. The routing mechanism controls which controller receives which requests. Typically, each controller has multiple routes, and different routes can perform different operations.

To create a basic controller, we use classes and decorators. The decorator associates the class with the required metadata and enables Nest to create a route map (binding the request to the appropriate controller).

/ * user.module.ts * / create a user mod import {Module} from'@ nestjs/common'; import {UserController} from'. / user.controller'; import {UserService} from'. / user.service'; @ Module ({controllers: [UserController], providers: [UserService],}) export class UserModule {} / * app.module.ts * / finally introduce moduleimport {Module} from'@ nestjs/common' written by ourselves into app.module Import {AppController} from'. / app.controller';import {AppService} from'. / app.service';import {UserModule} from'. / user/user.module';@Module ({imports: [UserModule], controllers: [AppController], providers: [AppService],}) export class AppModule {}

The controller is ready to use, but Nest still doesn't know if UserController exists, so it won't create an instance of this class.

The controller always belongs to the module, which is why we include the controllers array in the @ Module () decorator. Since we have not defined any modules other than the root module AppModule, we will use it to introduce UserController

Use postman to see the effect.

You can see that sending a get request is a success.

Next, we use post put delete to send requests in turn to see how nest accepts and processes them.

Post

User.service file

/ * user.service.ts * / first create a user service service file import {Injectable} from'@ nestjs/common'; @ Injectable () / here setUser (sid: string, body: any): any {if (sid = = '123456') {return {msg:' set successfully', body,};}}

User.controller file

/ * user.controller.ts * / create a user controller file import {Controller, Get, Query} from'@ nestjs/common';import {UserService} from'. / user.service';@Controller ('user') export class UserService {@ Post (' set') setUser (@ Body () body: any, @ Query () query: any) {return this.userService.setUser (query.sid, body);}}

Use postman to see the effect.

You can see that sending a post request is a success.

Put

User.service file

/ * user.service.ts * / first create a user service service file import {Injectable} from'@ nestjs/common'; @ Injectable () / here updateUser (sid: string, body: any): any {if (sid = = '123456') {return {msg:' set successfully', body,};}}

User.controller file

The Param decorator @ Param () is used to modify the parameters of a method (params in the example above) and to use the routing parameters as properties of the decorated method parameters within the method. As the code above shows, we can access the id parameter (in the routing path) by referring to params.id. You can also pass a specific parameter tag to the decorator and then reference the routing parameter directly by parameter name in the method body.

/ * user.controller.ts * / create a user controller file import {Body, Controller, Get, Param, Post, Put, Query} from'@ nestjs/common';import {UserService} from'. / user.service';@Controller ('user') export class UserService {@ Put (': sid') updateUser (@ Param ('sid') sid: string, @ Body () body: any) {return this.userService.updateUser (sid, body);}}

Use postman to see the effect.

You can see that sending a put request is a success.

Delete

User.service file

/ * user.service.ts * / first create a user service service file import {Injectable} from'@ nestjs/common'; @ Injectable () / here deleteUser (sid: string): any {if (sid = = '123456') {return {msg:' deleted successfully',};}}

User.controller file

/ * user.controller.ts * / create a user controller file import {Body, Controller, Get, Param, Post, Put, Query} from'@ nestjs/common';import {UserService} from'. / user.service';@Controller ('user') export class UserService {@ Delete (': sid') deleteUser (@ Param ('sid') sid: string) {return this.userService.deleteUser (sid);}}

Use postman to see the effect.

You can see that sending a delete request is a success.

Read here, this "how to use the Nest.js framework in node" article has been introduced, want to master the knowledge of this article also need to practice and use to understand, if you want to know more about the article, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report