Why is express' res.download() method causing a “request aborted” error?

后端 未结 1 717
无人及你
无人及你 2021-01-27 04:34

I have the following code from a node.js server that uses the express framework:

var fs = require(\'fs\')
    express = require(\'expre         


        
相关标签:
1条回答
  • 2021-01-27 05:07

    You're not allowing res.download() to finish

    The Error: Request aborted means that express hasn't had a chance to finish sending what it needs to send.

    When you call res.download(), it's equivalent to performing res.send() except making sure it has adequate headers for the browser to know it's a file download, instead of something to display in the browser. This function call is asynchronous, meaning that it will continue running in the background and then run the next line of code, which in this case, is next().

    next() gets called, which then tells express to continue looking for routes that match, or, in this case, there are no more routes that match and express will terminate the connection. This is not what you want, as you're still trying to finish the file download. You don't need express tell you when you're done, you say when you're done.

    How to fix it?

    Very simply, just make sure that express cannot continue to the next route in the middleware if the route isn't /. Add an else clause to your conditional:

    app.use(function(req, res, next){
       var pathUrl = req.path;
       if(pathUrl !== '/') {
           res.download(__dirname + '/' + 'download.png', 'download.png', function(err){
              console.log(err);
           });
       } else {
           next();
       }
    });
    

    Footnote

    This is not the easiest way to accomplish what you're trying to do here. You can use wildcard route matching (*) to make this much simpler. I've given your code a little tidy up that includes some of these features.

    const path = require("path");
    const express = require("express");
    const app = express();
    
    app.get("/", (req, res) => res.send(`<a href="/download.png">download</a>`));
    
    app.get("*", (req, res) => {
        res.download(path.join(__dirname, "./download.png"), "download.png", err => {
            if (err) console.log(err);
        });
    });
    
    app.listen(3001);
    
    • (req, res) => {} is a cleaner way of writing function(req, res) {}
    • the path module should be used as it can handle multiple OS's
    • the * wildcard route will match anything, and should usually always go last
    • we now check to see if there is an err before we console.log() it
    0 讨论(0)
提交回复
热议问题