如何在res.redirect('/')之后执行一个动作,或者发送信息?

How to perform an action after, or send information in res.redirect('/')?

背景信息

问题

基本上:我想将用户重定向到 'website.com/' 的主页,但我采用的方法没有奏效。

主要方法:

if (res.locals.downloadFile2 === true) { 
    res.download(file2) 
}

但是: res.locals.downloadFile2 === undefined 当检查完成时。我试过单步执行,但在我正在使用的其中一个 _modules 中它正在某处被重置,所以这是行不通的。我目前不确定原因。

我可能 解决 这个问题,方法是在用户通过身份验证之前不显示 link,然后 不应该 任何重定向到登录并再次返回的情况,这意味着他们永远不会看到登录页面等,但这不是解决这个问题的正确方法,也不是我想要实现的。

非常感谢任何帮助,如果需要,我可以提供更多信息!

提前致谢。

问题是,在重定向之后,res 对象是一个全新的对象,因为浏览器发出了遵循重定向的新请求。这就是为什么 res.locals.downloadFile2undefined.

要解决您的问题,您可以将代码 res.local.downloadFile2 = true 替换为设置 cookie 的代码。 cookie 保存的信息将由浏览器存储在客户端,并随每个请求发送到服务器。

参见 cookies npm 包示例:

var Cookies = require('cookies');
var cookies = new Cookies(req, res, { keys: ['arbitrary string to encrypt the cookie'] })    

// get value of the cookie
var need_to_download_file = cookies.get('need_to_download_file', { signed: true })

// Logic to download file (if necessary)
if (need_to_download_file) {
    // Trigger download of the file
    // Reset cookie
    cookies.set('need_to_download_file', false, { signed: true })
}

// set the cookie 
cookies.set('need_to_download_file', true, { signed: true })