gpt4 book ai didi

javascript - Express.js 无法读取未定义的属性 'req'

转载 作者:数据小太阳 更新时间:2023-10-29 03:59:20 25 4
gpt4 key购买 nike

我的 Express.js 应用一直在抛出 Cannot read property 'req' of undefined。本质上,它监听 GET 请求,获取 content 查询,然后用表格回复。以下是出现问题的部分。

index.js

var panels = require('./modules/panels.js');
app.get('/panel', function (req, res) {
var user;
if (user = req.session.user) {
panels.getContents(req.query.content, user.innId, res.send);
} else {
res.sendStatus(401);
}
});

modules/panels.js

exports.getContents = function(panelName, innId, callback) {
var response = "";
switch (panelName) {
case 'tenants':
con.query(queryString, queryParams, function(err, rows) {
if (err) {
handle(err);
} else {
if (rows.length == 0) {
var tenants = 0;
var debtors = 0;
} else {
var tenants = rows[0].tenants;
var debtors = rows[0].length;
}
response = convertToHTMLTable(rows);
}
callback(response); /*THE ERROR POINTS HERE */
});
break;

/* other cases here */

default:
response += "Invalid Request";
callback(response);
}
}

我做错了什么?我的猜测是我不应该将 res.send 作为回调传递。那么,我该如何解决呢?

最佳答案

我也遇到过这个错误,在仔细阅读错误消息并盯着我的代码看了太久之后,它点击了。

我(和上面的提问者)的代码看起来像这样:

  somethingAsync
.then(res.send) // <-- storing send() divorced from parent object "res"
}

问题是当稍后调用 res.send 时,它脱离了它的动态作用域——这意味着在 send 方法中调用 this,通常指的是 res,现在指的是 global。显然,res.send 包含对 this.req 的引用,给出了错误消息。

等效场景:

res = {
send: function() {
console.log(this.originalMessage.req);
},
originalMessage: { req: "hello SO" },
};

res.send();
// # "hello SO"
const x = {};
x.send = res.send;
x.send();
// # Uncaught TypeError: Cannot read property 'req' of undefined

或者,换句话说:

new Promise(_ => _())
.then(_ => console.log(this.msg.req));
// # Uncaught (in promise) TypeError: Cannot read property 'req' of undefined

两种解决方案:

handler(req, res) {
somethingAsync
.then(() => res.send())
// ^ send will be called as a method of res, preserving dynamic scope
// that is, we're storing a function that, when called, calls
// "res.send()", instead of storing the "send" method of "res" by itself.
}

理论上更惯用的方法是

handler(req, res) {
somethingAsync
.then(res.send.bind(res))
//^ res is explicitly bound to the saved function as its dynamic scope
}

动态作用域的有害小陷阱,那个。似乎 express 应该放弃那里的动态范围,或者至少抛出一个更好的错误......

关于javascript - Express.js 无法读取未定义的属性 'req',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41801723/

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