使用Node.JS下载文件时出现奇怪的错误

jsed 发布于 2019-03-09 download 最后更新 2019-03-09 14:40 4 浏览

这是Node.JS代码,它有两部分。第一个是在主服务器文件中:

app.get('/download/:photo', function (req, res){
dbs.imagenschema.find({ _id: req.params.photo }, function (err, imagen){
if (err) throw assert.ifError(err);;
var file = __dirname + '/public/users/' + imagen.auid + '/' + imagen.name;
var filename = path.basename(file);
     var mimetype = mime.lookup(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
     res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
     filestream.pipe(res);
});
});
另一部分是dbs.imagenschema,但该部分非常简单,它只是从dbs模块导出的图像的模式。 这是按钮,当点击时,下载开始:
<a href="/download/<%= photo._id %>">
  <button class="btn btn-inverse"><i class="icon-download-alt icon-white"></i>  Download</button>
</a>
但是,当我点击它时,我收到这个错误:
TypeError: Cannot read property 'background' of null
  at eval (eval at <anonymous> (/root/pixgalery/node_modules/ejs/lib/ejs.js:234:12), <anonymous>:30:4196)
  at /root/pixgalery/node_modules/ejs/lib/ejs.js:239:15
  at Object.exports.render (/root/pixgalery/node_modules/ejs/lib/ejs.js:277:13)
  at View.exports.renderFile [as engine] (/root/pixgalery/node_modules/ejs/lib/ejs.js:303:22)
  at View.render (/root/pixgalery/node_modules/express/lib/view.js:75:8)
  at Function.app.render (/root/pixgalery/node_modules/express/lib/application.js:500:10)
  at ServerResponse.res.render (/root/pixgalery/node_modules/express/lib/response.js:717:7)
  at /root/pixgalery/app.js:181:15
  at Promise.<anonymous> (/root/pixgalery/db.js:237:27)
  at Promise.<anonymous> (/root/pixgalery/node_modules/mongoose/lib/promise.js:133:8)
所以,我认为是因为这个原因:
app.get('/:user/:id', function (req, res){
dbs.getimage(req.params.id, req.params.user, function (user, img, fav, comments){
if (img.type == 'music') {
res.render('music.ejs', {
user: user,
            photo: img,
            req: req.session.user,
            fav: fav,
            comments: comments
});
} else{
res.render('photo.ejs', {
user: user,
            photo: img,
            req: req.session.user,
            fav: fav,
            comments: comments
});
}
});
});
也许服务器认为/download/fooid是我上面写的代码的请求,因为/download/fooid不会发送任何响应给EJS文件,所以不可能得到这样的错误。任何解决方案? 感谢提前!
已邀请:

bquos

赞同来自:

您必须确保在/:user/:id路线之前声明/download/:photo路线,否则后者也将匹配/download/fooid,认为download是用户参数而fooidid参数(使用Express,匹配按声明顺序发生:第一条路线匹配请求将处理它)。 所以:

// first this...
app.get('/download/:photo', ...);
// ...and then this.
app.get('/:user/:id', ...);