【发布时间】:2019-11-18 20:37:33
【问题描述】:
我正在使用 Node.js,并且正在执行一个带有承诺的数据库调用。我设置了一个 '.then/.catch' 来处理承诺的结果。这部分似乎没有任何问题。在对从数据库返回的数据进行一些处理后,我试图“重定向”到“.then”语句中的另一条路由。这种重定向似乎导致“.catch”语句出现问题。如果我删除“res.redirect”,我没有错误问题...有解决方法吗?任何建议表示赞赏。
代码:
const db = require('./routes/queries');
//**Query PostGres database...
db.getMembers()
.then(function(value) {
console.log('Async success!', value);
//do some processing on the data returned from the promise call here...
//if I insert a redirect here...such as "res.redirect('/_members');"...
//I get a "Caught an error! ReferenceError: res is not defined" message...?
//evidently the redirect fires the '.catch' statement below...why?
})
.catch(function(err) {
console.log('Caught an error!', err);
});
【问题讨论】:
-
嗯,错误信息似乎很清楚。你在哪里定义
res? -
我正在使用带有 Express 的 Node.js...我在代码中有许多 res.redirect 语句,没有一个会导致任何问题...只有在我的 promise resolve 语句中... “res.redirect”是标准 Express 功能的一部分。感谢您的回复。
-
你能在这里显示更多上下文吗?更具体地说, res 来自哪里以及它会发生什么?它可能与异步性有关? res失去范围? Idk,就像我说的那样,我们必须看到完整的上下文才能分辨出来。
-
重定向到另一条路线似乎抛出了'.catch'语句...有没有办法在'.then'中重定向页面导航...?
-
那么我只能假设此代码位于未定义
res的请求处理程序之外。res不是一个只存在的神奇变量。 您在定义请求事件处理程序时声明它(例如api.get('/foo', function (req, res) { ... }))。您有责任将其传递到需要的地方。
标签: javascript node.js redirect promise