1

I have a rest api that serves images. Each url will always return the same file, eg: https://example.com/rest/file/organisation/table/1234.jpg. However the actual files do not reside under the www filesystem. As a result it appears that express always resends the files with a 200 status.

How do I get Express to return 304 after the first time the image is downloaded?

Here's the express code I'm using:

router.get('/file/:organisation/:table/:filename', function (req, res, next) {
  db.resolveTableName( req )
  .then( table => {
      const pathname = path.resolve( MediaPath ) + '/' + req.params.organisation + '/'
        + req.params.table + '/' + req.params.filename;

      // Get the filetype
      readChunk( pathname, 0, 4100 )
      .then( buffer => {
        var mimetype = fileType( buffer ).mime;
        if( mimetype === 'image/jpeg' ) {
          var s = fs.createReadStream( pathname );
          s.on('open', function () {
            res.set('Content-Type', mimetype);
            s.pipe(res);
          });
          s.on('error', function () {
            res.set('Content-Type', 'text/plain');
            res.status(404).end('Not found');
          });
        } else {
          res.status(500).json( 'Invalid file type' );
        }
      })
      .catch( err => {
        res.status(500).json( 'Error on ' + req.params.filename );
      });
  })
  .catch( err => {
    res.status(401).json('Unauthorized');;
  });
});

I've looked here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Principles, and wondered if this is the right way to go?

minisaurus
  • 1,099
  • 4
  • 17
  • 30

0 Answers0