简体   繁体   中英

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. 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:

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). 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> .

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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