0

Getting req.param undefined

Hi, I have a similar error to the one above.

server.get('/:file_id', function(req , res) {
  var file_id = req.params.id;
  console.log(file_id);
  gfs.files.find({_id: file_id}).toArray(function (err, files) {
    if (err) {
      res.json(err);
    }
    if (files.length > 0) {
      var mime = files[0].contentType;
      var filename = files[0].filename;
      res.set('Content-Type', mime);
      res.set('Content-Disposition', "inline; filename=" + filename);
      var read_stream = gfs.createReadStream({_id: file_id});
      read_stream.pipe(res);
    } else {
      res.json(file_id+ '  This file does not exist.');
    }
  });
});

Below is a ejs file that gets file_id to server.

<div class="card card-body mb-3">
    <%= file.filename %>
          <form action="/:<%= file._id %>" method="get">
            <input type="submit" value="DOWNLOAD" class="btn btn-primary btn-block">
          </form>
  </div>

What I get from this code is : "undefined This file does not exist." I think the problem lies on req.params.id but am not sure where to fix.

Thank you.

OneBite
  • 13
  • 4
  • 1
    You have defined the route like: `/:file_id` therefore the key in the req.params object will be `file_id` too. – Palladium02 Jul 04 '22 at 13:51
  • Have you tried `req.params.file_id`? – ClassHacker Jul 04 '22 at 13:51
  • Thank you guys! ":62bb571d71c40d24ea68b589 This file does not exist." is what I get by @ClassHacker 's code. This is much better, but do you know how I can actually make it download? – OneBite Jul 04 '22 at 14:09

0 Answers0