代码之家  ›  专栏  ›  技术社区  ›  Epple

在ExpressJS/NodeJS中使用类ES6时出现问题[重复]

  •  -1
  • Epple  · 技术社区  · 1 年前

    我使用类在ExpressJS中实现中间件,但在调用方法时遇到了问题。首先,我正在运行下面的代码,然后我仍然收到 res req 来自的对象 applyMiddleware 但在 handleMiddleware 我试图得到的方法 要求 雷斯 但这将导致错误:

    TypeError:无法读取未定义的属性(正在读取 '我的中间件')

    为什么我会出现这个错误?这个错误的原因是什么?它似乎只发生在类中,而不发生在函数中。

    我的代码:

    class MyMiddleware {
      constructor() {}
      
      handleMiddleware(req, res) {
         // cannot get req & req
         console.log('Request incoming: ', req);
         console.log('Response outcoming: ', res);
      }
    
      applyMiddleware(req, res, next) {
         console.log(req, res); // oke, everything is printed
    
         this.handleMiddleware(req, res);
         next();
      }
    }
    
    export default MyMiddleware;
    

    在Express中应用上述中间件:

    const app = express();
    const middleware = new MyMiddleware();
    app.use(middleware.applyMiddleware)
    
    ...more code...
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   XMehdi01    1 年前

    问题是 this 未被保留,这会在您调用它时导致错误,因此 要解决此问题,可以使用箭头函数:

    handleMiddleware = (req, res) => {
        //code...
    }
    

    或者您可以使用 .bind(this) 方法绑定正确的 调用函数时的上下文:

    handleMiddleware(req, res) {
    console.log('handleMiddleware Request and Response:', req, res);
    }
    
    applyMiddleware(req, res, next) {
        console.log(req, res);
        this.handleMiddleware.bind(this)(req, res);
        next();
    }