簡體   English   中英

節點中的摘要(req,res,next)

[英]abstract (req, res, next) in node

說我有一條路線:

app.get(abc, (req, res, next) => {
    if (req.params.ID === undefined) { 
        res.status(400); 
        res.end(); 
    }
    next();
});

我想知道如果我將if語句抽象到另一個文件中是否也能如此工作:

let undefinedID = (req, res, next) => {
    if (req.params.ID === undefined) {
        res.status(400); 
        res.end();
    }
    next();
}

module.exports = {undefinedID};

然后在我的路線內調用該函數:

const reqConditionals = require('path/to/fxn');

app.get(abc, () => {
    reqConditionals.undefinedID();
});

我想要這樣做的原因是因為我有很多路由具有類似的請求條件和響應,並希望開始對其進行重構。 因此,如果我這樣操作,是否會一樣工作?

是的,你可以這么做。 但是你這樣做是這樣的:

const reqConditionals = require('path/to/fxn');

app.get(abc, reqConditionals.undefinedID);

然后,您可以擁有實際的路線。

app.get(abc, reqConditionals.undefinedID);
app.get(abc, (req, res, next) => {
  //here you know that the id is not undefined cause the previous middleware let you reach here.
});

此外,您可以將其應用於數組或其他任何功能,並具有多個功能。

app.get([abc, def], reqConditionals.undefinedID, reqConditionals.undefinedFoo, reqConditionals.undefinedBar);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM