2

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!

mottosson
  • 3,283
  • 4
  • 35
  • 73

1 Answers1

1

You should use get() on your imageRouter.js Router and prefix it on your main app.

use() is for middlewares.

Here is imageRouter.js:

var router = require('express').Router();
var fs = require('fs');

router.get('/:filename', function(req, res) {
  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');
  }
});

module.exports = router;

And your server.js:

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

var ImageRouter = require('./routes/imageRouter');

app.use('/api/image', ImageRouter);
Arnaud Rinquin
  • 4,296
  • 1
  • 30
  • 51
  • Works like a charm. Thanks alot! – mottosson Jun 23 '15 at 18:59
  • Those who need to reference a URL parameter like `/:name' in another file, check this question: http://stackoverflow.com/questions/28977253/express-router-undefined-params-with-router-use-when-split-across-files – George May 13 '16 at 00:06