• express中间件分三类


    中间件一般都是通过i修改req 或res对象来为后续的处理提供遍历的使用

    中间件分类 next 放行函数

    • use(function(req,res,next){})
    • use('请求路径',function(req,res,next){})
    • get('请求路径',function(req,res,next){})
    • post('请求路径',function(req,res,next){})

    错误日记处理方式

    const express=require('express')
    const fs = require('fs')
    const app=express();
    
    // parse application/x-www-form-urlencoded
    app.use(express.urlencoded({ extended: false }))
    
    // parse application/json
    app.use(express.json())
    
    app.use((req,res,next)=>{
         res.header("Content-Type", "application/json; charset=utf-8")
         next()
    })
    
    app.get('/', (req, res) => {
        //通过JSON.parse解析查询字符串中的某个
        try {
            const data = JSON.parse('{abc');
            res.json(data);
        } catch (e) {
            const error_log = `
            错误名:${e.name}
            错误消息:${e.message}
            错误堆栈:${e.stack}
            错误时间:${new Date()}
            `
            fs.appendFile('./err_log.txt', error_log, (err) => {
                res.writeHead(500, {})
                res.end('500 服务器正忙,请稍后重试')
            })
        }
    })
    
    
    app.get('/a', (req, res, next) => {
        fs.readFile('./a.text', (err, data) => {
            if (err) {
                //这里调用的next会被app.use((err,req,res,next))这个中间件匹配到
                next(err)
            }
        })
    })
    
    //该中间件只有被带有参数的next才能调用到
    app.use((err, req, res, next) => {
        const error_log = `
        错误名:${e.name}
        错误消息:${e.message}
        错误堆栈:${e.stack}
        错误时间:${new Date()}
        `
        fs.appendFile('./err_log.txt', error_log, (err) => {
            res.writeHead(500, {})
            res.end('500 服务器正忙,请稍后重试')
        })
    })
    
    //404处理中间件
    app.use((req,res,next)=>{
        res.end('404')
    })
    
    app.listen(3000,()=>{
        console.log('server start and listen at 3000')
    })
  • 相关阅读:
    winRT Com组件开发流程总结
    win32 COM组件编写
    windows8 APP开发的远程调试
    VS2012中,C# 配置文件读取 + C#多个工程共享共有变量 + 整理using语句
    STL源码--序列式容器
    代码规范
    Visual Studio Code 断点调试配置方法(请按我的步骤 一定可以做到)
    CSS层级关系 学习笔记
    VUE 学习笔记
    CSS 学习笔记
  • 原文地址:https://www.cnblogs.com/lvlisn/p/14932842.html
Copyright © 2020-2023  润新知