gpt4 book ai didi

node.js - Expressjs。从原型(prototype)函数调用构造函数中的函数时出现类型错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:20:07 24 4
gpt4 key购买 nike

我试图从原型(prototype)调用构造函数中的函数,但不断收到以下错误,我不知道我的代码出了什么问题。

TypeError: this.authorize is not a function

这是我的代码: Controller .js

var Controller = function() {
this.authorize = function(req, res) {
if (!req.user) {
res.redirect("/");
}
};
};
Controller.prototype.online = function(req, res) {
this.authorize(req, res);
res.render('./play/online');
};
var controller = new Controller();
module.exports = controller;

路由.js

var router = require('express').Router();
var controller = require('../controller');

router.get('/online', controller.online);
module.exports = router;

如果我将授权函数放在 Controller 之外,那么我可以调用它,但我不想这样做。那我能做什么呢?

更新:
当我应用请求“/online”时,在 Nodejs 中发生此错误,而不是在纯 Javascript 中发生此错误

最佳答案

online 作为回调传递时,您会丢失上下文

router.get('/online', controller.online.bind(controller));

或者在构造函数内部

var Controller = function() {
this.authorize = function(req) {
console.log(req);
};

this.online = this.online.bind(this);
};

关于node.js - Expressjs。从原型(prototype)函数调用构造函数中的函数时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44818173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com