簡體   English   中英

可以在不使用中間件函數的情況下增強express.js req和res變量嗎?

[英]It is possible to enhance the express.js req and res variables without using a middleware function?

我正在使用express.js在一個寧靜的服務工作,我想增強req和res變量,所以例如你可以寫類似的東西

app.use(function (req, res, next) {
    res.Ok = function (data) {
        res.status(200).send(data);
    };

    res.InternalError = function (err) {
        res.status(500).send(err);
    };
});

然后

router.get('/foo', function (req, res) {
    res.Ok('foo');
})

這將在響應正文中發送'foo'並將狀態代碼設置為200並且工作正常。

我的第一個問題是,如果可以在沒有中間件功能的情況下添加這樣的功能,那么可以說在屬性或app變量的原型中?

第二個問題是,如果在應用程序級別添加許多具有中間件功能的功能,則會出現性能問題。 此功能是按請求附加到請求和響應對象還是在應用程序啟動時附加一次?

我知道Sails框架已經這樣做了,但我想知道他們是否也使用中間件功能。

我一直在挖掘並發現請求和響應對象使用__proto__屬性在express中公開。

var express = require('express'),
app = express();

app.response.__proto__.foo = function (data) {
    this.status(200).send(data);
};

后來在路由器中

router.get('/foo', function (req, res, next) {
    res.foo('test');
});

這將在您的瀏覽器中打印測試,因此可以在不使用任何中間件的情況下添加功能。

注意:我確信這種方法存在一些缺點(例如,覆蓋表達預定義的屬性),但出於測試目的和添加非常簡單的功能,我認為在性能方面稍微好一點。

我不知道除了使用中間件之外的任何其他方式。 但在我看來,你可以做到以下幾點來實現幾乎相同的事情。

// Some Route
router.get('/foo', function(req, res, next) {
 // ...
 if(err) {
   res.status(500);
   return next(err);
 }
 return res.send('ok');
});

// Another route
router.get('/bar', function(req, res, next) {
  // ...
  if(badUserId) {
    res.status(400);
    return next('Invalid userId.');
  }
  req.result = 'hello';
  return next();
});

router.use(function(req, res) {
  // I prefer to send the result in the route but an
  // approach like this could work
  return res.send(req.result);
});

// Error Middleware
router.use(function(err, req, res, next) {
  if(res.statusCode === 500) {
    // Log the error here
    return res.send('Internal server error');
  } else {
    return res.send(err);
  }
});

暫無
暫無

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

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