在 expressjs 中,使用中间件层通过类来处理传入的调用
/middlewares/index.js
class Middlewares {
constructor(options) {
this.options = options;
}
general(req, res, next) {
console.log(this.options)
}
test() {
console.log(this.options)
}
}
export default Middlewares;
在app.js
import express from 'express';
import { createServer } from 'http';
import Middlewares from './middlewares/index.js'
const app = express();
const options = {
whiteListSite: ['http://localhost:81', 'http://localhost:83'],
};
const server = createServer(app);
const middlewares = new Middlewares(options);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(middlewares.general); //<-- получаю ошибку TypeError: Cannot read properties of undefined (reading 'options')
middlewares.test() //<-- здесь срабатывает все, в консоль выводиться { whiteListSite: [ 'http://localhost:81', 'http://localhost:83' ] }
app.get('/', function(req, res) {
res.send('hello world');
});
server.listen(8080, () => {
console.log(`GateWay app listening on port ${8080}`);
});
在服务器操作期间,当触发处理程序时,即对路由发出任何请求时,函数中general都会生成错误TypeError: Cannot read properties of undefined (reading 'options'),但是当我调用 test() 时,一切都正常运行,没有失败
也就是说,类的函数不能从类构造函数中获取变量。这和什么有关?
该错误与调用上下文丢失有关。
您还忘记调用 next() 函数,该函数会激活应用程序中的下一个中间处理函数。
为了修复这个错误,我建议以下几种方法
首先,使用闭包并将其传递给单独的变量
其次,使用箭头函数,因为它们没有自己的背景
当然,你也可以明确地将上下文绑定到你的通用方法版本
然而,我不太喜欢这种方法