Table of Contents
1.Express framework introduction
Home Web Front-end JS Tutorial A brief discussion on how to use Node third-party framework Express

A brief discussion on how to use Node third-party framework Express

May 23, 2022 pm 08:34 PM
nodejs node.js node express

This article will take you to learn about the third-party framework ExpressNode, and briefly talk about how to use the Express framework well. I hope it will be helpful to everyone!

A brief discussion on how to use Node third-party framework Express

1.Express framework introduction

  • ##1.Express is developed by

    Nodejs A very heavyweight third-party framework, it is to the NodeJS server what Jquery is to the HTML client.

    • If you don’t even know how to use Express, you are basically embarrassed to tell others that you know NodeJS
  • ##2 .Express official website:
    • www.expressjs.com.cn/
    • expressjs.com/
    • General When we learn a new technology, we always go to the official website documentation to view its API, and then try a lot. Practice makes perfect
  • 3. Express’s github address: https://github.com/expressjs/express
  • The original author of Express, TJ, is very famous in the node community. He has written more than 200 frameworks. Currently, he has handed over Express to a friend for maintenance. , announced that it will no longer maintain the NodeJS framework and switch to the Go language (https://github.com/tj)
  • 4. The Express official website introduces itself like this: Based on Node. js platform, a fast, open and minimalist web development framework.
    • A very important highlight of Express is that it does not change the existing features of nodejs, but expands on it

        In other words, using Express you can use any nodejs native API, or you can use Express’s API
  • 5. The three core functions of Express

      #1. Hosting static resources
    • The nodejs implementation of static server discussed on the second day The function only requires one line of code in express
      ##2. Routing
    • express has its own routing function, making Node server development extremely simple

        express supports chain syntax, which can make the code look more concise
      ==3. Middleware==
    • The core technology and idea of ​​Express, everything is middleware
      • Although middleware is a bit difficult to understand, it is very convenient to use, similar to

        bootstrap plug-in
          .
  • 2. Download express

Download instructions:

npm i express

If your website is very slow, you can use npm config set registry registry.npm.taobao.org/ to increase the speed

     就是淘宝帮你把这个东西下载淘宝的服务器上,然后你在淘宝服务器上下载
Copy after login

A brief discussion on how to use Node third-party framework Express3.Use Express

//1.导入模块
const express = require('express')

//2.创建服务器
/* express() 相当于http模块的http.createServer() */
const app = express()


//3.接收客户端请求
/*(1)express最大的特点就是自带路由功能,我们无需在一个方法中处理所有请求
		* 路由:一个请求路径对应一个方法(函数)
   (2)在express中,每一个请求都是一个单独的方法
 */

app.get('/',(req,res)=>{
    //响应客户端数据

    //express响应数据 send方法:自动帮我们设置好了响应头,无需担心中文乱码问题
    res.send('月下风起')

})

app.get('/heroInfo',(req,res)=>{
    
    res.send({
        name:'张三',
        age:20
    })
})

//4.开启服务器
app.listen(3000,()=>{
    console.log('服务器启动成功')
})
Copy after login
4-Express to respond to client data

//1.导入模块
const express = require('express')

//2.创建服务器
/* express() 相当于http模块的http.createServer() */
const app = express()


//3.接收客户端请求

//文本类型数据
app.get('/',(req,res)=>{
    //响应客户端数据
    res.send('月下风起')
})

//json格式数据
app.get('/info',(req,res)=>{
    //express自动帮我们将js对象转成json响应给客户端
    res.send({
        name:'张三',
        age:20
    })
})

//文件类型数据
app.get('/login',(req,res)=>{
    res.sendFile(__dirname + '/login.html')
})

//4.开启服务器
app.listen(3000,()=>{
    console.log('服务器启动成功')
})
Copy after login
5.Express Hosting static resources

http://expressjs.com/en/starter/static-files.html
//1.导入模块
const express = require('express');

//2.创建服务器
const app = express()

//托管静态资源(相当于我们之前写的静态资源服务器)
/* 
1.当请求路径为/时,express会自动读取www文件夹中的index.html文件响应返回
2.当路径请求为www文件夹中的静态资源,express会自动拼接文件路径并响应返回
*/
app.use(express.static('www'))

//4.开启服务器
app.listen(3000,()=>{
    console.log('success')
})
Copy after login

6. Use of third-party middleware

1. On the Express official website, there are many third-party middleware, which can make our Nodejs development extremely simple
  • Middle It is a plug-in for the front-end of software. After use, it will add members to req or res in express
    2. All third-party framework learning routines are the same
  • 1. Go to the official website and check the documentation

      2. CTRL C and CTRL V
    3. Use of third-party middleware The steps are generally two fixed steps
  • One: Install
      npm i xxxx
    • (copy and paste from the official website)

      Third party Middleware needs to be installed using npm, which can be understood as a special third-party module
      2: Use
    • app.use(xxx)
    • (Official website copy and paste)

body-parse Third-party middleware: parse post request parameters
  • Install body-parser:

    npm install body-parser
    • https://www.npmjs.com/package/body-parser

    • //导入模块
      const express = require('express')
      //创建服务器
      const app = express()
      
      //使用第三方中间件
      /*所有的第三方模块思路都是一样 
          1.进官网,查文档
          2.找examples(使用示例),复制粘贴
              a.安装第三方模块:`npm i body-parser`
              b.使用中间件: arr.use(具体用法请复制粘贴) 
      使用body-parser中间件之后,你的req会增加一个body属性,就是你的post请求参数
      */
      //(1)导入模块
      const bodyParser = require('body-parser')
      // parse application/x-www-form-urlencoded 
      //(2)使用中间件
      app.use(bodyParser.urlencoded({ extended: false }))
      //解析json参数
      app.use(bodyParser.json())
      
      app.post('/abc',(req,res)=>{
          console.log(req.body)
          //告诉客户端我收到的参数
          res.send(req.body)
      })
      
      app.post('/efg',(req,res)=>{
          console.log(req.body)
          //告诉客户端我收到的参数
          res.send(req.body)
      })
      
      //开启服务器
      app.listen(3000, () => {
          console.log('success');
      })
      Copy after login
      For more node-related knowledge, please visit: nodejs tutorial!

      The above is the detailed content of A brief discussion on how to use Node third-party framework Express. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles