Table of Contents
Routing
The routing in image-gallery-express is handled by Express.js routers. There are 3 routers; index.js
, upload.js
, and gallery.js
. index.js
routes for the home page, and this was generated by the Express Application Generator. The other two routers route for /upload/
and /gallery/
respectively. Technically, only one router is ever needed, but it makes sense to have routers responsible for different paths like /upload/
and /gallery/
, which is what I have done here.
// routes/upload.js
const express = require('express');
const router = express.Router();
// Controller modules
const uploads_controller = require('../controllers/uploads_controller');
// Routes
router.get('/', uploads_controller.upload_get)
router.post('/', upload.single('upload'), function(req, res) {
uploads_controller.upload_post(req, res);
});
module.exports = router;
// routes/gallery.js
const express = require('express');
const router = express.Router({ strict: true });
// Controller modules
const gallery_controller = require('../controllers/gallery_controller');
// Routes
router.get('/', gallery_controller.gallery_index);
router.get('/:id', gallery_controller.gallery_show);
module.exports = router;
Notice how the routers are importing a controller module. This is not a strict requirement as Express.js is unopinionated, meaning the design of the code is entirely up to the coder. I did this because I was used to the MVC pattern. Also notice how the post route in upload.js
has two callbacks. The first callback is for the Multer middleware, which is responsible for uploading files. For more information, check out the uploading section.
The actual request is to be handled by the controllers (or other middlewares like Multer). I believe it is bad practice to have a router module do all the work.
Routers are then used by app.js
.
// app.js
const indexRouter = require('./routes/index');
const uploadRouter = require('./routes/upload');
const galleryRouter = require('./routes/gallery');
const app = express();
app.use('/', indexRouter);
app.use('/upload', uploadRouter);
app.use('/gallery', galleryRouter);