内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

Node.js中什么是Express中間件-創(chuàng)新互聯(lián)

這篇文章主要介紹Node.js中什么是Express中間件,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

創(chuàng)新互聯(lián)建站為您提適合企業(yè)的網(wǎng)站設(shè)計?讓您的網(wǎng)站在搜索引擎具有高度排名,讓您的網(wǎng)站具備超強的網(wǎng)絡(luò)競爭力!結(jié)合企業(yè)自身,進行網(wǎng)站設(shè)計及把握,最后結(jié)合企業(yè)文化和具體宗旨等,才能創(chuàng)作出一份性化解決方案。從網(wǎng)站策劃到成都網(wǎng)站建設(shè)、成都做網(wǎng)站, 我們的網(wǎng)頁設(shè)計師為您提供的解決方案。

什么是 Express 中間件?

  • 中間件在字面上的意思是你在軟件的一層和另一層中間放置的任何東西。
  • Express 中間件是在對 Express 服務(wù)器請求的生命周期內(nèi)所執(zhí)行的函數(shù)。
  • 每個中間件都可以訪問其被附加到的所有路由的 HTTP 請求和響應(yīng)。
  • 另外,中間件可以終止 HTTP 請求,也可以用 next 將其傳遞給另一個中間件函數(shù)。中間件的這種“鏈”使你可以對代碼進行劃分并創(chuàng)建可重用的中間件。

編寫 Express 中間件的要求

你需要安裝一些東西來創(chuàng)建、使用和測試 Express 中間件。首先需要 Node 和 NPM。為確保已經(jīng)安裝,可以運行:

npm -v && node -v

你應(yīng)該看到已安裝的 Node 和 NPM 版本。如果出現(xiàn)錯誤,則需要安裝 Node。所有例子都應(yīng)在 Node ver 8+ 和NPM ver 5+ 下使用。

本文使用了 Express 4.x 版。這很重要,因為從 3.x 版到 4.x 版有重大的更改。

Express中間件:基礎(chǔ)

首先我們使用 Express 最基本的內(nèi)置中間件。創(chuàng)建一個新項目并 npm 初始化它…

npm init
npm install express --save

Create server.js and paste the following code:

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

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

app.listen(3000);

中間件解決什么問題?為什么要用它?

假設(shè)你在 web 網(wǎng)絡(luò)服務(wù)器上正在使用 Node.js 和 Express 運行Web應(yīng)用程序。在此應(yīng)用中,你需要登錄的某些頁面。

當(dāng) Web 服務(wù)器收到數(shù)據(jù)請求時,Express 將為你提供一個請求對象,其中包含有關(guān)用戶及其所請求數(shù)據(jù)的信息。 Express 還使你可以訪問響應(yīng)對象,可以在Web服務(wù)器響應(yīng)用戶之前對其進行修改。這些對象通??s短為 req,res。

中間件函數(shù)是使用相關(guān)信息修改 reqres 對象的理想場所。例如用戶登錄后,你可以從數(shù)據(jù)庫中獲取其用戶詳細信息,然后將這些詳細信息存儲在 res.user 中。

中間件函數(shù)是什么樣的?

async function userMiddleware (req, res, next) {
    try {
        const userData = await getUserData(req.params.id);  //see app.get below

        if(userData) {
                req.user = userData;
                next();
        }
    } catch(error)  {
        res.status(500).send(error.message); //replace with proper error handling
    }
}

如果出現(xiàn)錯誤,并且你不想執(zhí)行其他代碼,則不要調(diào)用該函數(shù)。請記住在這種情況下要發(fā)送響應(yīng),否則客戶端將會等待響應(yīng)直到超時。

var app = express();

//your normal route Handlers
app.get('/user/:id', userMiddleware, userController);

中間件鏈

你可以在中間件數(shù)組中或著通過使用多個 app.use 調(diào)用來鏈接中間件:

app.use(middlewareA);
app.use(middlewareB);
app.get('/', [middlewareC, middlewareD], handler);

Express 收到請求后,與請求相匹配的每個中間件都將會按照初始化的順序運行,直到有終止操作為止。

Node.js中什么是Express中間件

因此,如果發(fā)生錯誤,則將按順序調(diào)用所有用于處理錯誤的中間件,直到其中一個不再調(diào)用 next() 函數(shù)調(diào)用為止。

Express中間件的類型

  • 路由器級中間件,例如:router.use
  • 內(nèi)置中間件,例如:express.static,express.json,express.urlencoded
  • 錯誤處理中間件,例如:app.use(err,req,res,next)
  • 第三方中間件,例如:bodyparser、cookieparser
  • 路由器級中間件
  • express.Router 使用 express.Router 類創(chuàng)建模塊化的、可安裝的路由處理。路由實例是一個完整的中間件和路由系統(tǒng)。

    • 你可以用中間件進行日志記錄、身份驗證等操作。如下所示,以記錄用戶的最新活動并解析身份驗證標(biāo)頭,用它確定當(dāng)前登錄的用戶并將其添加到 Request 對象。
    • 該函數(shù)在程序每次收到請求時執(zhí)行。如果有錯誤,它會僅結(jié)束響應(yīng),而不會調(diào)用后續(xù)的中間件或路由處理。
var router = express.Router()
//Load router-level middleware by using the router.use() and router.METHOD() functions.
//The following example creates a router as a module, loads a middleware function in it,
//   defines some routes, and mounts the router module on a path in the main app.
var express = require(‘express’);
var router = express.Router();

// a middleware function with no mount path. This code is executed for
//   every request to the router
// logging
async function logMiddleware (req, res, next) {
    try {
         console.log(req.user.id, new Date());
     next();
    } catch() {
        res.status(500).send(error.message);
    }
}
// authentication
    async function checkAuthentication(req, res, next) => {
// check header or url parameters or post parameters for token
const token = req.body.token || req.query.token || req.headers['x-access-token']
 || req.headers['authorization'];
      if (token) {
        try {
            // verifies secret
            req.decoded = await jwt.verify(token, config.secret)

            let checkUser = await authenticateTokenHelper.getUserDetail(req);

            // if everything is good, save to request for use in other routes
                if (checkUser) {
                        req.user = req.decoded
                        next()
                } else {
                    return res.status(403).json({ 
                    message: responseMessage.noAuthorized 
                    })
                }
        } catch (err) {
            return res.status(401).json({ message: responseMessage.invalidToken })
        }
  } else {
    // if there is no token
    return res.status(400).json({ message: responseMessage.invalidRequest })
  }
}
router.use(logMiddleware);
    router.get('/user, checkAuthentication, handler);
內(nèi)置中間件

Express 有以下內(nèi)置的中間件功能:

  • express.static 提供靜態(tài)資源,例如 HTML 文件,圖像等。
  • express.json 負載解析用 JSON 傳入的請求。
  • express.urlencoded 解析傳入的用 URL 編碼的有效載荷請求。
錯誤處理中間件

錯誤處理中間件始終采用四個參數(shù)(err,req,res,next)。你必須通過提供四個參數(shù)來將其標(biāo)識為錯誤處理中間件函數(shù)。即使你不需要使用 next 對象,也必須指定。否則 next 對象將被解釋為常規(guī)中間件,并將會無法處理錯誤?;竞灻缦滤荆?/p>

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

例1:

app.get('/users', (req, res, next) => {
  next(new Error('I am passing you an error!'));
});
app.use((err, req, res, next) => {
  console.log(err);    
  if(!res.headersSent){
    res.status(500).send(err.message);
  }
});

在這種情況下,管道末端的錯誤處理中間件將會處理該錯誤。你可能還會注意到,我檢查了 res.headersSent 屬性。這只是檢查響應(yīng)是否已經(jīng)將標(biāo)頭發(fā)送到客戶端。如果還沒有,它將向客戶端發(fā)送 HTTP 500  狀態(tài)和錯誤消息。

例2:

你還可以鏈接錯誤處理中間件。通常以不同的方式處理不同類型的錯誤:

app.get('/users, (req, res, next) => {
  let err = new Error('I couldn\'t find it.');
  err.httpStatusCode = 404;
  next(err);
});

app.get('/user, (req, res, next) => {
  let err = new Error('I\'m sorry, you can\'t do that, Dave.');
  err.httpStatusCode = 304;
  next(err);
});

app.use((err, req, res, next) => {
   // handles not found errors
  if (err.httpStatusCode === 404) {
    res.status(400).render('NotFound');
  }
   // handles unauthorized errors 
  else if(err.httpStatusCode === 304){
    res.status(304).render('Unauthorized');
  }
    // catch all
   else if (!res.headersSent) {
     res.status(err.httpStatusCode || 500).render('UnknownError');
  }
  next(err);
});
  • 在這種情況下,中間件檢查是否拋出了 404(not found)錯誤。如果是,它將渲染 “NotFound” 模板頁面,然后將錯誤傳遞到中間件中的下一項。
  • 下一個中間件檢查是否拋出了 304(unauthorized)錯誤。如果是,它將渲染“Unauthorized”頁面,并將錯誤傳遞到管道中的下一個中間件。
  • 最后,“catch all” 錯誤處理僅記錄錯誤,如果未發(fā)送響應(yīng),它將發(fā)送錯誤的 httpStatusCode(如果未提供則發(fā)送 HTTP 500 狀態(tài))并渲染 “UnknownError” 模板。
第三方級別的中間件

在某些情況下,我們將向后端添加一些額外的功能。先安裝 Node.js 模塊獲取所需的功能,然后在應(yīng)用級別或路由器級別將其加載到你的應(yīng)用中。

示例:當(dāng) body-parser 處理 Content-Type 請求標(biāo)頭時,所有中間件都將使用解析的正文填充 req.body 屬性。

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.post('/save',(req,res)=>{
    res.json({
        "status":true,
         "payload":req.body
    })
}
app.listen(3000,(req,res)=>{
    console.log('server running on port')
})

以上是Node.js中什么是Express中間件的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道!

新聞標(biāo)題:Node.js中什么是Express中間件-創(chuàng)新互聯(lián)
當(dāng)前地址:http://www.rwnh.cn/article18/djhdgp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設(shè)計公司小程序開發(fā)、域名注冊、網(wǎng)站排名用戶體驗響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站
黄石市| 仙游县| 上虞市| 洪雅县| 连平县| 乌兰察布市| 陆河县| 平阳县| 临泽县| 遂溪县| 叙永县| 鄂伦春自治旗| 无为县| 铅山县| 西乌珠穆沁旗| 安丘市| 宁远县| 武陟县| 中江县| 威宁| 瑞丽市| 南昌县| 静乐县| 云林县| 武乡县| 大新县| 佛冈县| 永泰县| 石河子市| 靖安县| 洞头县| 神池县| 响水县| 比如县| 南城县| 济源市| 会理县| 元氏县| 连城县| 中方县| 宁晋县|