简体   繁体   English

Node.js和Express-登录并下载后重定向

[英]Node.js and Express - Redirect after Login and Download

I have an express app that allows a user to login and download data files. 我有一个快速应用程序,允许用户登录和下载数据文件。 There is also a home page after the login. 登录后还有一个主页。 If a user enters the URL to a specific file without logging in, the app will first ask the user to login, which is by design. 如果用户未登录就输入特定文件的URL,则该应用程序将首先要求用户登录(这是设计使然)。 However, after the user logs in, the file is downloaded without redirecting the user to the home page. 但是,在用户登录后,将下载文件而不会将用户重定向到主页。 I was wondering if there's a way to allow the user to login, redirect to the home page, and then download the file with one click after the user logs in. It's kind of confusing now because the user is stuck on the login page after successfully logging in and downloading the file. 我想知道是否有一种方法可以允许用户登录,重定向到主页,然后在用户登录后一键下载文件。这有点令人困惑,因为用户在成功登录后仍停留在登录页面上登录并下载文件。 Below is a snippet of the code. 下面是代码片段。 I am using express 4.x: 我正在使用express 4.x:

app.get('/dat/:file(*)', routes.ensure_authenticated, function(req, res, next) {
  var path = __dirname + '/public/dat/' + req.params.file;
  res.download(path);
});
app.use('/', serveStatic(__dirname + '/public'));

// dat directory requests
app.use('/dat', routes.ensure_authenticated, serveIndex( 'public/dat', { icons: true }));

I can't think a way of doing it server-side only. 我无法想到仅在服务器端执行此操作的方法。

You could trigger client-side the redirection to the download. 您可以触发客户端到下载的重定向。

Something like redirecting to /#download=link_or_id and parsing the hash with JavaScript to get the final download link (the link_or_id thing). 诸如重定向到/#download=link_or_id并使用JavaScript解析哈希以获取最终的下载链接( link_or_id )。 Then, after the download is triggered, remove the hash from location so the download isn't triggered again when the user reloads the page. 然后,在触发下载后,从位置删除哈希值,这样当用户重新加载页面时不会再次触发下载。

Also, instead of using JavaScript, you could do something similar redirecting to /?download=link_or_id and server-side inserting a meta refresh tag inside <head> . 另外,除了使用JavaScript,您还可以执行类似的重定向到/?download=link_or_id并在服务器端在<head>内插入一个meta refresh标签。

You could programmatically send an ajax GET request from the client side via a setTimeout or on document load, so it would be something like: 您可以通过setTimeout或在文档加载时以编程方式从客户端发送ajax GET请求,因此类似于:

$(function() {
   $.get('/dat/filename', function(){
      //enter code here
   });
 }):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM