简体   繁体   中英

Nodejs - Express res.download giving Can't set headers after they are sent exception

I want to make an api that will serve files of any extensions. Like this: http://localhost/download/[file].[extension]

Here is my code, but it is intermittently giving this message: Can't set headers after they are sent.

  var express = require('express');
  var app = express();

  app.get('/download/:fileName/:extension', function(req, res){
    var file = __dirname + '/' + req.params.fileName + '.' + req.params.extension;
    res.download(file, function(err){
        if (err) {
          res.sendStatus(404);
        }
      res.end();
    }); 
  });

  var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('app listening at http://%s:%s', host, port);
  });

res.download has already sent a response (Not always true in the case of an error though)

You can fix this by doing

res.download(file, function(err){
  if(err) {
    // Check if headers have been sent
    if(res.headersSent) {
      // You may want to log something here or do something else
    } else {
      return res.sendStatus(SOME_ERR); // 404, maybe 500 depending on err
    }
  }
  // Don't need res.end() here since already sent
}

Other changes called out in the comments above:

  • download uses sendFile , which you don't need res.end() after
  • download 's documentation warns that you need to check res.headersSent when handling errors, as the headers may already be sent, which would mean you can't change the status

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