Node tutorial-simple tutorial of Express framework

Express framework learning

(Introduction) Introduction to Framework

This is also a development framework, is a third-party module, using this framework can easily create a website server

Let's take a look at its features: 1. Provide a convenient and concise route definition 2. Simplify the processing of obtaining HTTP request parameters 3. High degree of support for template engine, easy to render dynamic HTML pages 4. Provide middleware The mechanism effectively controls HTTP requests (interception of requests) 5. Has a large number of third-party middleware to extend the function

In fact, the framework is some APIs, and the learning framework is to learn and familiar with its API

Compare the native routing and the processing implementation method of obtaining the request parameters

  • Simple to get started
  1. First of all, we want to download npm
 npm install express
  1. Introduce the express module, this returns a constructor, which is one of our express core APIs
const express = require('express');
  1. Create a server and listen on the port
  2. Create a route and accept the request
// 引入express框架
const express = require('express'); //返回的值 是一个方法!
// 创建网站服务器
const app = express();

app.get('/', (req, res) => {
    // send()
    // 1. send方法内部会检测响应内容的类型
    // 2. send方法会自动设置http状态码
    // 3. send方法会帮我们自动设置响应的内容类型及编码
    res.send('Hello. Express');
})

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

// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');

(2) Middleware

What is middleware? ? This is a bunch of methods, to preprocess the request bluntly. You can set up multiple middlewares to process the same data stream, and they have different execution processing order. The middleware is just a valve!

Composition of middleware

There are mainly two parts: the method provided by Express, the second is the processing function (callback). Mainly we have a next

Grammatical structures

 app.get('/request', (req, res, next) => {
     req.name = "张三";
//next方法就是是否允许把请求传递给下一个处理中间件,直到结束

next();
 });
 app.get('/request', (req, res) => {
     res.send(req.name);
 });

app.user middleware

This is a middleware. It is special. It does not distinguish the request method. It must be placed in front of all middleware. He can hand over the controller, if you write next it will be stuck

Grammar examples

// 引入express框架
const express = require('express');
// 创建网站服务器
const app = express();

// 接收所有请求的中间件
// app.use 接收请求, 但是不指定请求方式get或者poset,只要哟请求就有这个东西,如何next传递走
app.use((req, res, next) => {
    console.log('请求走了app.use中间件');
    next()
})

// 这里我们的第一个请求做了 规定,当客户端访问/request请求的时候走当前中间件
app.use('/request', (req, res, next) => {
    console.log('请求走了app.use / request中间件')
    next()
})

// 如果你访问的list那么值钱的user use('/request', (req, res, next)就不会走了
app.get('/list', (req, res) => {
    res.send('/list')
})

app.get('/request', (req, res, next) => {
    req.name = "张三";
    next();
})

app.get('/request', (req, res) => {
    res.send(req.name)
})

// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');


Middleware applications

Very widely used:

Route guard, route protection, when the client accesses the page that needs to log in, it can first make the middleware determine the user's login status. If the user is not logged in, the request is intercepted and the user is directly prohibited from entering the page that needs to be logged in.

The website maintenance announcement defines the middleware that receives all requests at the top of all routes to respond directly to the client. The website is under maintenance.

Custom 404 page

Sample code block

// 引入express框架
const express = require('express');
// 创建网站服务器
const app = express();

// // 网站公告
// app.use((req, res, next) => {
//     res.send('当前网站正在维护...')
// })

//只要你想访问管理页面,就拦截下来 判断你是否登录登录了就放开你,没有的话,就戒掉你
app.use('/admin', (req, res, next) => {
    // 用户没有登录
    let isLogin = true;
    // 如果用户登录
    if (isLogin) {
        // 让请求继续向下执行
        next()
    } else {
        // 如果用户没有登录 直接对客户端做出响应
        res.send('您还没有登录 不能访问/admin这个页面')
    }
})

app.get('/admin', (req, res) => {
    res.send('您已经登录 可以访问当前页面')
})

// 这里的逻辑就是:如果你所有的路由页面都没有匹配到就过来这里,告你没有找到对应的资源
app.use((req, res, next) => { //app.use就是指定匹配路由
    // 为客户端响应404状态码以及提示信息
    res.status(404).send('当前访问的页面是不存在的')
})

// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');


Error handling middleware

In the process of program execution, some unpredictable errors will inevitably occur, such as file read failure and database connection failure. Error handling middleware is a place where errors are handled centrally. It receives errors thrown from elsewhere

When an error occurs in the program, the next () method is called, and the error information is passed to the next () method in the form of parameters to trigger the error handling middleware.

How to define an error handling middleware?

  • Lost and common errors and how can asynchronous code supporting Promise Api be captured and thrown to the processing middleware?
// 引入express框架
const express = require('express');
const fs = require('fs');
// 创建网站服务器
const app = express();
//注意!我们的错误有两种,一种是同步的错误,一种是异步的错误,处理方式是不一样的。异步错误可以
//通过回调函数捕获,也可以通过try catch捕获。但是这个不能捕获其他的api
app.get('/index', (req, res, next) => {
    // throw new Error('程序发生了未知错误')
    fs.readFile('./01.js', 'utf8', (err, result) => {
        if (err != null) {
            next(err)//这个就是异步的解决方式 如果发生了错误就把这个erro传出去给错误处理中间件
        } else {
            res.send(result)
        }
    })
    // res.send('程序正常执行')
})

// 错误处理中间
app.use((err, req, res, next) => {
    res.status(500).send(err.message);
})

// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');

  • How to catch asynchronous function errors? And handling, note that it cannot catch other errors

// 引入express框架
const express = require('express');
const fs = require('fs');

const promisify = require('util').promisify;

// 这个的把原理的方法包装了起来,放回一个方法
const readFile = promisify(fs.readFile);
// 创建网站服务器
const app = express();

app.get('/index', async(req, res, next) => {
    try {
        await readFile('./aaa.js')
    } catch (ex) {
        next(ex); //把这个错误传递走
    }
})

// 错误处理中间
app.use((err, req, res, next) => {
    res.status(500).send(err.message);
})

// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');


(3) Routing

Basic code for building modular routing

We want to separate the route, the business processing logic of some pages is a different route

Simple creation

// 引入express框架
const express = require('express');
// 创建网站服务器
const app = express();
// 创建路由对象
const home = express.Router();
// app.use是一个中间件
// 为路由对象匹配请求路径
app.use('/home', home);
// 创建二级路由
home.get('/index', (req, res) => {
    res.send('欢迎来到博客首页页面')
})

// 端口监听
app.listen(3000);

Building modular routing

This refers to the main code that separates the routing

  • hoem.js routing
const express = require('express');

const home = express.Router();

home.get('/index', (req, res) => {
	res.send('欢迎来到博客首页页面')
});

module.exports = home;
  • admin.js routing
const express = require('express');

const admin = express.Router();

admin.get('/index', (req, res) => {
	res.send('欢迎来到博客管理页面')
});

module.exports = admin;

  • app.js routing
// 引入express框架
const express = require('express');
// 创建网站服务器
const app = express();

const home = require('./route/home');
const admin = require('./route/admin');
// 配置模块化路由

app.use('/home', home);
app.use('/admin', admin);


// 端口监听
app.listen(3000);

(4) Processing of requested data

Two comparisons, one is a native implementation and the other is a framework implementation

How to get get request parameters

You can get GET parameters by req.query, and the GET parameters will be converted into objects and returned within the framework.

Grammatical structures

// 接收地址栏中问号后面的参数
 // 例如: http://localhost:3000/?name=zhangsan&age=30
 app.get('/', (req, res) => {
    console.log(req.query); // {"name": "zhangsan", "age": "30"}
 });



How to get post request parameters

Receiving post request parameters in Express requires the help of a third-party package body-parser

Grammatical structures


 // 引入body-parser模块
 const bodyParser = require('body-parser');
 
 // 配置body-parser模块,拦截所有请求,会把请求转化为对象,然后给这日些对象添加一个属性这个属性叫body。这个extended:false参数是false的时候说明 先用queryString系统模块对参数处理一遍。true的时候使用名为QS的第三方模块 把请求转化为对象
//  bodyParser.urlencoded({ extended: false })放回的一个函数
 
 app.use(bodyParser.urlencoded({ extended: false }));
 // 接收请求
 app.post('/add', (req, res) => {
    // 接收请求参数
    console.log(req.body);
 }) 


The parameter in app.use () is a function ~

Verification code


// 引入express框架
const express = require('express');
const bodyParser = require('body-parser');
// 创建网站服务器
const app = express();
// 这个是一个对象,里面是的a是2 {a :2}
app.use(fn({ a: 2 })) //user可以直接使用函数

function fn(obj) {
    return function(req, res, next) {
        if (obj.a == 1) {
            console.log(req.url)
        } else {
            console.log(req.method)
        }
        next() //移交控制权
    }
}

//路由
app.get('/', (req, res) => {
    // 接收post请求参数
    res.send('ok')
})

// 端口监听
app.listen(3000);

Routing parameters (this is also a request processing analysis function)

This is easier to use, it is specially used to deal with the parameters of get

This is something that compares nb, and is also a request parameter


// 引入express框架
const express = require('express');
const bodyParser = require('body-parser');
// 创建网站服务器
const app = express();

// 这额: id: name实际上是一个占位符号
app.get('/index/:id/:name/:age', (req, res) => {
    // 接收post请求参数。这个属性 是expers框架下的构建的,parmas存储的就是一个值对象

    res.send(req.params) // 你拿到的是{ id:123 ,name:laoli,age:18 }
})

//你的发送格式: localhost:3000/index/123/laoli/18
// 端口监听
app.listen(3000);

(V. Resources) Static resource access function

Guess you like

Origin www.cnblogs.com/BM-laoli/p/12673929.html