Getting Started with Node.js - Getting to Know Express

1 Introduction

The content of this article comes from bilibili dark horse programmers

2 What is express

  • The official concept: Express is based on Node.js 平台fast, open and minimalWeb 开发框架
  • Popular understanding: the function of Express is similar to the built-in http module of Node.js,是专门用来创建 Web 服务器的
  • The essence of Express: it is a third-party package on npm, which provides a convenient way to quickly create a web server.

3 The role of express

For front-end programmers, the two most common servers are:
Web server: a server that provides web page resources to the outside world.
API interface server: a server dedicated to providing API interfaces externally.
Using Express, we can easily and quickly create a server for a Web site or a server for an API interface.

4 Basic usage of express

4.1 Installation

In the diary where the project is located, run the following terminal command to install express into the project:

npm install express

4.2 Create a basic web server

// 1. 导入 express
const express = require('express')
// 2. 创建 web 服务器
const app = express()
// 3. 启动 web 服务器
app.listen(80, () => {
    
    
  console.log('express server running at http://127.0.0.1');
})

4.3 Listening to get requests

Through the app.get() method, you can monitor the client's GET request

// 参数1:客户端请求的 URL 地址
// 参数2:请求对应的处理函数
//       req:请求对象(包含了与请求相关的属性与方法)
//       res:响应对象(包含了与响应相关的属性与方法)
app.get('请求URL'(req, res) => {
    
     /*处理函数*/ })

4.4 Listening to post requests

Through the app.post() method, you can monitor the client's POST request

// 参数1:客户端请求的 URL 地址
// 参数2:请求对应的处理函数
//       req:请求对象(包含了与请求相关的属性与方法)
//       res:响应对象(包含了与响应相关的属性与方法)
app.post('请求URL'(req, res) => {
    
     /*处理函数*/ })

4.5 Respond the content to the client

Through the res.send() method, the processed content can be sent to the client

app.get('/user', (req, res) => {
    
    
  //向客户端发送 JSON 对象
  res.send({
    
     name: 'zs', age: 20, gender: '男' })
})

app.post('/user', (req, res) => {
    
    
  //向客户端发送文本内容
  res.send('请求成功')
})

4.6 Obtain the query parameters carried in the url

Through the req.query object, you can access the parameters sent by the client to the server in the form of a query string:

app.get('/', (req, res) => {
    
    
  // 通过 req.query 可以获取到客户端发送过来的查询参数
  res.send(req.query)
})

4.7 Get dynamic parameters in url

Through the req.params object, you can access the URL, through: the matched dynamic parameters:

app.get('/user:id', (req, res) => {
    
    
  // 通过 req.params 是动态匹配到的 url 参数,默认是空对象
  res.send(req.params)
})

5 Hosting static resources

5.1 Hosting a single static resource

express provides a very useful function called express.static(). Through it, we can easily create a static resource server. For example, the pictures, CSS files, and
JavaScript files in the public directory can be exported to the public through the following code Open access to:

app.use(express.static('public'))

5.2 Hosting multiple static resources

If you want to host multiple static resource directories, please call the express.static() function multiple times:
When accessing static resource files, the express.static() function will find the required files according to the order in which the directories are added.

app.use(express.static('public'))
app.use(express.static('files'))

5.3 Mount path prefix

If you want to mount the path prefix before the managed static resource access path, you can use the following method:

app.use('/public', express.static('public'))

6 nodemon

6.1 Why use nodemon

When writing and debugging a Node.js project, if you modify the code of the project, you need to close it manually frequently, and then restart it, which is very cumbersome.
Now, we can use the tool nodemon (https://www.npmjs.com/package/nodemon), which can monitor
changes in project files. When the code is modified, nodemon will automatically restart the project for us, which is very convenient development and debugging.

6.2 install nodemon

npm i -g nodemon

6.3 Using nodemon

# node app.js

nodemon app.js

7 The concept of routing

7.1 What is routing

Routing is the mapping relationship

7.2 Routing in Express

In Express, routing refers to the mapping relationship between client requests and server processing functions.
The routing in Express consists of three parts, which are the type of request, the URL address of the request, and the processing function. The format is as follows:

app.METHOD(PATH, HANDLER)

8 Use of routing

For this 方便对路由进行模块化的管理, Express does not recommend mounting routes directly on the app, but instead 推荐将路由抽离为单独的模块.
The steps to extract routing into a separate module are as follows:

  1. Create the .js file corresponding to the routing module
  2. Call the express.Router() function to create a routing object
  3. Mount a specific route to the route object
  4. Use module.exports to share routing objects externally
  5. Register the routing module with the app.use() function

app.js

const express = require('express')
const router = require('./router')

const app = express()

// app.use() 函数的作用,就是来注册全局中间件
app.use('/api', router)

app.listen(80, () => {
    
    
  console.log('your server is running at http://127.0.0.1');
})

router.js

const express = require('express')
const router = express.Router()

router.get('/user/list', (req, res) => res.send('get user list'))
router.post('/user/add', (req, res) => res.send('add new user'))

module.exports = router

Guess you like

Origin blog.csdn.net/weixin_36757282/article/details/128661108