Home > Web Front-end > JS Tutorial > body text

A deep dive into the Express framework in Node.js

青灯夜游
Release: 2021-06-28 09:47:17
forward
2277 people have browsed it

This article will give you a detailed introduction to the Express framework in Node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A deep dive into the Express framework in Node.js

Many languages ​​have some frameworks that can help us develop and maintain projects more quickly. For example, JS has popular frameworks such as Vue, React, and Angular; and Node .js is no exception, it also has some frameworks to help us develop Node.js projects.

Currently the more popular Node.js frameworks are Express, Koa and Egg.js. No matter which Node.js framework it is, It is implemented based on middleware, and the execution method of middleware needs to be based on the onion model. [Recommended learning: "nodejs tutorial"]

Onion model

Abstract explanation, to pass through the center point of the onion, you mustFirst penetrate the onion skin layer by layer into the center point, and then move outward layer by layer from the center point Penetrating the epidermis , here is a characteristic: How many layers of epidermis are penetrated when entering, how many layers of epidermis must be penetrated when exiting. It penetrates the epidermis first and then exits the epidermis. This structure is in line with the first-in-last-out principle of the stack structure.

In the Node.js framework, we can define the skin of the onion as middleware:

  • The process of entering the center point from the outside in is a keyword next()
  • From the inside out, after each middleware is executed, it enters the next layer of middleware, all the way to the last layer.

Let’s take a brief look at some Express frameworks!

Express

Express is a framework for HTTP services in Node.js. To understand a framework, it is best to A good way is to

  • understand its key functions
  • and deduce what problem it wants to solve

To understand its key functions, we can go to the Express website to view its Features. These core functions are all designed to make it more convenient and concise for us to write Provide HTTP service, thus greatly reducing our development burden and allowing us to quickly start development.

A deep dive into the Express framework in Node.js

##Some

Features:

    Routing: separate the corresponding routes as modules for processing
  • request/response The simplification of attributes allows us to use the corresponding attributes directly without conversion.
    • request: pathname, query, etc.
    • response: send() , json(), jsonp(), etc.
    ##Middleware (
  • next()
  • )Better organization of process code
    • Async breaks the onion model of
    • Express
# #Express Modify the rock-paper-scissors game

Now modify the rock-paper-scissors game by using the Express framework, game.js

game module and

index.html The code of the page has not changed, you can go to github and clone. index.js

To transform Express, you need to install

express first with npm: npm i express.

const fs = require('fs');
const express = require('express');

const game = require('./game');
let playerWon = 0; // 赢的次数

const app = express();

// 路由功能,将对应路由功能分开作为模块处理,到时候也可以放到其它文件去
// 通过 app.get 设定 /favicon.ico 路径的路由
// .get 代表请求 method 是 get,所以这里可以用 post、delete 等。这个能力很适合用于创建 rest 服务
app.get('/favicon.ico', function (request, response) {
  // 一句 status(200) 即可代替 writeHead(200); end();
  // response.writeHead(200);
  // response.end();
  response.status(200);
  return;
})
// 打开页面 index.html
app.get('/', function (request, response) {
  // fs.createReadStream(__dirname + '/index.html').pipe(response);
  // send接口会判断你传入的值的类型,文本的话则会处理为text/html
  // Buffer的话则会处理为下载,html文件需要加上 `utf-8`
  response.send(fs.readFileSync(__dirname + '/index.html', 'utf-8'))
})

// next()同步状态下没有问题的,但是一旦有了异步,洋葱模型就打破了
app.get('/game',
  function (request, response, next) {
    if (playerWon >= 3) {
      response.status(500);
      response.send('我不会再玩了!');
      return;
    }
    // 通过next执行后续中间件
    next();
    // 当后续中间件执行完之后,会执行到这个位置
    if (response.playerWon) {
      playerWon++;
    }
  },
  // 获取玩家的操作
  function (request, response, next) {
    // Express 中对 request 做了一些处理,可以直接拿到 query 参数
    // const query = querystring.parse(parsedUrl.query);
    // const playerAction = query.action;
    const query = request.query;
    const playerAction = query.action;
    response.playerAction = playerAction;
    // 通过next执行后续中间件
    next();
  },
  function (request, response) {
    // 通过 response 去挂载一些参数
    let playerAction = response.playerAction;
    // 执行游戏逻辑
    const gameRes = game(playerAction);
    // 先返回头部
    // response.writeHead(200);
    response.status(200);
    // 根据不同的游戏结果返回不同的说明
    if (gameRes == 0) {
      // response.end('平局!');
      response.send('平局!');
    } else if (gameRes == 1) {
      response.send('你赢了!');
      // 玩家胜利次数统计+1
      // playerWon++;
      response.playerWon = true;
    } else {
      response.send('你输了!');
    }
  }
)
app.listen(3000);
Copy after login
Code address: https://github.com/V-vincent/node-introduction

For more programming-related knowledge, please visit:

Programming video
! !

The above is the detailed content of A deep dive into the Express framework in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!