簡體   English   中英

在 node.js 上添加中間件 function 到 azure 函數

[英]adding a middleware function to azure functions on node.js

我正在嘗試在 azure function 上復制您可能在 express 中擁有的中間件。

例如:

router.get('/protectedEndpoint', secured(), function (req, res) {

其中secured() function 是一個中間件,如果有效,它將發送next()。

azure 的問題是它的風格

module.exports = function (context) {

我不確定如何在這個中使用 next() 運行中間件

這是 function 可能看起來像的一個愚蠢的例子:

module.exports = function () {
  return function secured (req, res, next) {
    if (req.user) { return next(); }
    req.session.returnTo = req.originalUrl;
    res.redirect('/login');
  };
};

使用 azure function 您可以像使用Express一樣使用azure-middleware引擎添加中間件。 通過這種方法,您可以執行與 Express 相同的操作。 該引擎的鏈接如下azure-middleware

var MiddlewareHandler =  require('azure-middleware')

module.exports = new MiddlewareHandler()
.use((ctx) => {
   secured();//Your middleware function
   ctx.next();
})
.use(async (ctx) => {
   //Your controller or your main function script
      ctx.log.info('Im called third');
      ctx.done(null, { status: 200 });
})
.catch((error, ctx, msg) => {
    ctx.log.info(error); // ERROR!
    ctx.next();
 })
.listen();

是的,頁面上的示例充其量是神秘的,事實證明,package 也沒有完整的 Typescript 支持。

如果閱讀本文的任何人正在尋找 Typescript 解決方案,您將必須采用嵌套的 try catch 語句來首先驗證令牌(如果用例是身份驗證),然后繼續使用服務調用任何受保護的資源。

暫無
暫無

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

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