国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

93 # 實現(xiàn) express 錯誤處理中間件

這篇具有很好參考價值的文章主要介紹了93 # 實現(xiàn) express 錯誤處理中間件。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

上一節(jié)實現(xiàn)了 express 的中間件,這一節(jié)來實現(xiàn)錯誤處理中間件

執(zhí)行某一步出錯了,統(tǒng)一規(guī)定調(diào)用 next 傳遞的參數(shù)就是錯誤信息

先看 express 實現(xiàn)的demo

const express = require("express");
const app = express();

app.use("/", (req, res, next) => {
    console.log("中間件1");
    // next();
    next("中間件1出錯了");
});

app.use("/", (req, res, next) => {
    console.log("中間件2");
    next();
    // next("中間件2出錯了");
});

app.use("/", (req, res, next) => {
    console.log("中間件3");
    next();
    // next("中間件3出錯了");
});

app.get(
    "/",
    (req, res, next) => {
        console.log("路由1");
        next();
    },
    (req, res, next) => {
        res.end("出錯了 *****");
    }
);

app.listen(3000, () => {
    console.log(`server start 3000`);
    console.log(`在線訪問地址:http://localhost:3000/`);
});

然后去訪問:http://localhost:3000/

93 # 實現(xiàn) express 錯誤處理中間件,Node / Node 框架,前端工程架構(gòu),express,中間件

錯誤處理中間價,里面必須要有 4 個 參數(shù)(取函數(shù)的長度),放到棧的最底下

app.use((err, req, res, next) => {
    res.end(err);
})

93 # 實現(xiàn) express 錯誤處理中間件,Node / Node 框架,前端工程架構(gòu),express,中間件

下面實現(xiàn)處理邏輯

router/index.js

const url = require("url");
const Route = require("./route");
const Layer = require("./layer");
const methods = require("methods");

function Router() {
    // 維護(hù)所有的路由
    this.stack = [];
}

Router.prototype.route = function (path) {
    // 產(chǎn)生 route
    let route = new Route();
    // 產(chǎn)生 layer 讓 layer 跟 route 進(jìn)行關(guān)聯(lián)
    let layer = new Layer(path, route.dispatch.bind(route));
    // 每個路由都具備一個 route 屬性,稍后路徑匹配到后會調(diào)用 route 中的每一層
    layer.route = route;
    // 把 layer 放到路由的棧中
    this.stack.push(layer);
    return route;
};

methods.forEach((method) => {
    Router.prototype[method] = function (path, handlers) {
        // 1.用戶調(diào)用 method 時,需要保存成一個 layer 當(dāng)?shù)罈V?/span>
        // 2.產(chǎn)生一個 Route 實例和當(dāng)前的 layer 創(chuàng)造關(guān)系
        // 3.要將 route 的 dispatch 方法存到 layer 上
        let route = this.route(path);
        // 讓 route 記錄用戶傳入的 handler 并且標(biāo)記這個 handler 是什么方法
        route[method](handlers);
    };
});

Router.prototype.use = function (path, ...handlers) {
    // 默認(rèn)第一個是路徑,后面是一個個的方法,路徑可以不傳
    if (typeof path === "function") {
        handlers.unshift(path);
        path = "/";
    }
    // 如果是多個函數(shù)需要循環(huán)添加層
    for (let i = 0; i < handlers.length; i++) {
        let layer = new Layer(path, handlers[i]);
        // 中間件不需要 route 屬性
        layer.route = undefined;
        this.stack.push(layer);
    }
};

Router.prototype.handle = function (req, res, out) {
    console.log("請求到了");
    // 需要取出路由系統(tǒng)中 Router 存放的 layer 依次執(zhí)行
    const { pathname } = url.parse(req.url);
    let idx = 0;
    let next = (err) => {
        // 遍歷完后沒有找到就直接走出路由系統(tǒng)
        if (idx >= this.stack.length) return out();
        let layer = this.stack[idx++];
        if (err) {
            console.log("統(tǒng)一對中間件跟路由錯誤處理");
            // 找錯誤處理中間件
            if (!layer.route) {
                // 如果是中間件自己處理
                layer.handle_error(err, req, res, next);
            } else {
                // 路由則跳過,繼續(xù)攜帶錯誤向下執(zhí)行
                next(err);
            }
        } else {
            // 需要判斷 layer 上的 path 和當(dāng)前請求路由是否一致,一致就執(zhí)行 dispatch 方法
            if (layer.match(pathname)) {
                // 中間件沒有方法可以匹配,不能是錯誤處理中間件
                if (!layer.route) {
                    if (layer.handler.length !== 4) {
                        layer.handle_request(req, res, next);
                    } else {
                        next();
                    }
                } else {
                    // 將遍歷路由系統(tǒng)中下一層的方法傳入
                    // 加速匹配,如果用戶注冊過這個類型的方法在去執(zhí)行
                    if (layer.route.methods[req.method.toLowerCase()]) {
                        layer.handle_request(req, res, next);
                    } else {
                        next();
                    }
                }
            } else {
                next();
            }
        }
    };
    next();
};

module.exports = Router;

layer.js

function Layer(path, handler) {
    this.path = path;
    this.handler = handler;
}

Layer.prototype.match = function (pathname) {
    if (this.path === pathname) {
        return true;
    }
    // 如果是中間件,進(jìn)行中間件的匹配規(guī)則
    if (!this.route) {
        if (this.path == "/") {
            return true;
        }
        // /aaaa/b 需要 /aaaa/ 才能匹配上
        return pathname.startsWith(this.path + "/");
    }
    return false;
};
Layer.prototype.handle_error = function (err, req, res, next) {
    if (this.handler.length === 4) {
        // 調(diào)用錯誤處理中間件
        return this.handler(err, req, res, next);
    }
    next(err); // 普通的中間件
};
Layer.prototype.handle_request = function (req, res, next) {
    this.handler(req, res, next);
};
module.exports = Layer;

route.js

const Layer = require("./layer");
const methods = require("methods");

function Route() {
    this.stack = [];
    // 用來描述內(nèi)部存過哪些方法
    this.methods = {};
}

Route.prototype.dispatch = function (req, res, out) {
    // 稍后調(diào)用此方法時,回去棧中拿出對應(yīng)的 handler 依次執(zhí)行
    let idx = 0;
    console.log("this.stack----->", this.stack);
    let next = (err) => {
        // 如果內(nèi)部迭代的時候出現(xiàn)錯誤,直接到外層的 stack 中
        err && out(err);
        // 遍歷完后沒有找到就直接走出路由系統(tǒng)
        if (idx >= this.stack.length) return out();
        let layer = this.stack[idx++];
        console.log("dispatch----->", layer.method);
        if (layer.method === req.method.toLowerCase()) {
            layer.handle_request(req, res, next);
        } else {
            next();
        }
    };
    next();
};
methods.forEach((method) => {
    Route.prototype[method] = function (handlers) {
        console.log("handlers----->", handlers);
        handlers.forEach((handler) => {
            // 這里的路徑?jīng)]有意義
            let layer = new Layer("/", handler);
            layer.method = method;
            // 做個映射表
            this.methods[method] = true;
            this.stack.push(layer);
        });
    };
});

module.exports = Route;

測試demo

const express = require("./kaimo-express");
const app = express();

app.use("/", (req, res, next) => {
    console.log("中間件1");
    next();
    // next("中間件1出錯了");
});

app.use("/", (req, res, next) => {
    console.log("中間件2");
    // next();
    next("中間件2出錯了");
});

app.use("/", (req, res, next) => {
    console.log("中間件3");
    next();
    // next("中間件3出錯了");
});

app.get(
    "/",
    (req, res, next) => {
        console.log("路由1");
        next();
    },
    (req, res, next) => {
        res.end("出錯了 *****");
    }
);

// 錯誤處理中間價
app.use((err, req, res, next) => {
    console.log("錯誤處理中間價----->", err);
    res.end(err);
});

app.listen(3000, () => {
    console.log(`server start 3000`);
    console.log(`在線訪問地址:http://localhost:3000/`);
});

93 # 實現(xiàn) express 錯誤處理中間件,Node / Node 框架,前端工程架構(gòu),express,中間件文章來源地址http://www.zghlxwxcb.cn/news/detail-730397.html

到了這里,關(guān)于93 # 實現(xiàn) express 錯誤處理中間件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • express中間件當(dāng)做前端服務(wù)器的安全漏洞處理

    使用express當(dāng)做node服務(wù)器時,發(fā)現(xiàn)安全漏洞,記錄處理步驟: PS:以下安全內(nèi)容處理,需要使用到redis進(jìn)行會話存儲、請求計數(shù)、請求唯一限制等。為盡量確保開發(fā)環(huán)境與部署環(huán)境一致,請開發(fā)環(huán)境安裝并啟動Redis服務(wù)。 ** 此文檔只是說明記錄關(guān)鍵步驟。具體實現(xiàn)代碼可參照附

    2024年03月27日
    瀏覽(27)
  • Express中間件

    Express中間件

    客戶端發(fā)起的任何請求,到達(dá)服務(wù)器之后,都會觸發(fā)的中間件 多個局部生效的中間件 ? 中間件必須在路由之前注冊 ? 應(yīng)用中間件 路由中間件 錯誤級別中間件 ???????????? 錯誤級別中間件必須在所有路由之后 內(nèi)置中間件 舉例:express.json() 08.中間件-自定義中間件_嗶哩

    2024年02月13日
    瀏覽(17)
  • express框架中間件

    express框架中間件

    說明:Express框架中間件是指在處理HTTP請求前或后對請求和響應(yīng)進(jìn)行處理的函數(shù)。具體而言,中間件可以: 執(zhí)行一些公共的邏輯,比如身份驗證、日志記錄、錯誤處理等。 修改請求和響應(yīng),比如緩存、壓縮等。 控制請求流,比如路由控制、URL重定向等。 Express中間件可以是一

    2024年02月13日
    瀏覽(24)
  • 初識express/路由/中間件

    初識express/路由/中間件

    ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ???????? ? ? ? ?

    2024年02月11日
    瀏覽(44)
  • 【Express】文件上傳管理 multer 中間件

    Multer是Node.js中用于處理文件上傳的中間件。它可以幫助你處理文件上傳的相關(guān)邏輯,如接收和保存上傳的文件、限制文件大小、設(shè)置文件類型限制等。只能用于處理 multipart/form-data 類型的表單數(shù)據(jù),它主要用于上傳文件。 下面是使用Multer中間件的基本步驟: 安裝multer:在命

    2024年02月07日
    瀏覽(24)
  • 編寫中間件以用于 Express 應(yīng)用程序

    編寫中間件以用于 Express 應(yīng)用程序

    中間件 函數(shù)能夠訪問請求對象?( req )、響應(yīng)對象?( res ) 以及應(yīng)用程序的請求/響應(yīng)循環(huán)中的下一個中間件函數(shù)。下一個中間件函數(shù)通常由名為? next ?的變量來表示。 中間件函數(shù)可以執(zhí)行以下任務(wù): 執(zhí)行任何代碼。 對請求和響應(yīng)對象進(jìn)行更改。 結(jié)束請求/響應(yīng)循環(huán)。 調(diào)用堆棧

    2024年02月10日
    瀏覽(21)
  • node中間件-koa框架

    安裝 npm i koa koa導(dǎo)出的是一個類,必須用 new 進(jìn)行創(chuàng)建 koa也是通過注冊中間件來完成請求操作的 koa注冊的中間件提供了兩個參數(shù): ctx:上下文(Context)對象; koa并沒有像express一樣,將req和res分開,而是將它們作為ctx的屬性; ctx代表一次請求的上下文對象; ctx.reque

    2024年02月16日
    瀏覽(33)
  • 第九篇:node靜態(tài)文件服務(wù)(中間件)

    第九篇:node靜態(tài)文件服務(wù)(中間件)

    ????江城開朗的豌豆 :個人主頁 ????個人專欄? :《 VUE 》?《 javaScript 》 ??? ?個人網(wǎng)站? :《 江城開朗的豌豆?? 》? ???生活的理想,就是為了理想的生活?! 當(dāng)今互聯(lián)網(wǎng)時代,Node.js 成為了最受歡迎的服務(wù)器端開發(fā)平臺之一。作為一名小白,學(xué)習(xí) Node.js 可能會讓你感

    2024年02月20日
    瀏覽(18)
  • cool Node后端 中實現(xiàn)中間件的書寫

    cool Node后端 中實現(xiàn)中間件的書寫

    1.需求 在node后端中,想實現(xiàn)一個專門鑒權(quán)的文件配置,可以這樣來解釋 就是 有些接口需要token調(diào)用接口,有些接口不需要使用token 調(diào)用? 這期來詳細(xì)說明一下 ? ? ?什么是中間件中間件顧名思義是指在請求和響應(yīng)中間,進(jìn)行請求數(shù)據(jù)的攔截處理,數(shù)據(jù)校驗,并且進(jìn)行邏輯處理

    2024年02月20日
    瀏覽(25)
  • Node.js 使用 cors 中間件解決跨域問題

    Node.js 使用 cors 中間件解決跨域問題

    cors 是 Express 的一個第三方中間件。通過安裝和配置 cors 中間件,可以很方便地解決跨域問題。 CORS (Cross-Origin Resource Sharing,跨域資源共享)由一系列 HTTP 響應(yīng)頭 組成, 這些 HTTP 響應(yīng)頭決定瀏覽器是否阻止前端 JS 代碼跨域獲取資源 。 瀏覽器的 同源安全策略 默認(rèn)會阻止網(wǎng)

    2024年01月20日
    瀏覽(61)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包