I have an working api for serving images in a route in my server.js and want to abstract it to a separate module.
before:
app.get('/api/image/:filename', function(req, res){
var resourcePath = 'uploads/public/projectnumber/issues/small/' + req.params.filename + '.png';
console.log(resourcePath)
if(fs.existsSync(resourcePath)) {
var file = fs.readFileSync(resourcePath);
res.writeHead(200, 'Content-Type:application/pdf:image/png');
res.end(file,'binary');
}
else {
res.send(400, 'No image found');
}
})
I want something like this:
var ImageRouter = require('./routes/imageRouter');
app.use('/api/image/:filename', ImageRouter);
and I've tried writing it like this in my imageRouter.js file:
var express = require('express');
var fs = require('fs');
var router = express.Router();
router.use(function(req, res, next) {
var resourcePath = 'public/images/' + req.params.filename + '.png';
if(fs.existsSync(resourcePath)) {
var file = fs.readFileSync(resourcePath);
res.writeHead(200, 'Content-Type:application/pdf:image/png');
res.end(file,'binary');
}
else {
res.send(400, 'No image found');
}
next();
});
module.exports = router;
But req.params.filename is undefined. Where have I gone wrong?
Thanks!