这是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文件的任何响应,因此,不可能得到这样的错误。对此有何解决方案?
谢谢你的进步!
答案 0 :(得分:1)
您必须确保在/download/:photo
路线之前宣布/:user/:id
路线,否则后者也匹配/download/fooid
,认为{{1} }}是用户参数,download
是fooid
参数(使用Express,匹配按声明顺序发生:匹配请求的第一个路由将处理它)。
所以:
id