I have the following code from a node.js
server that uses the express
framework:
var fs = require(\'fs\')
express = require(\'expre
res.download()
to finishThe 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.
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();
}
});
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(`download`));
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) {}
path
module should be used as it can handle multiple OS's*
wildcard route will match anything, and should usually always go lasterr
before we console.log()
it