O'Reilly logo

Hands-On Microservices with Node.js by Diogo Resende

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using route parameters

Now that we've written more than 100 lines of code, let's take a step back and look at it. There's certainly space for optimizations. Let's use another awesome feature of Express – route parameters. They allow you to preprocess any route that uses a parameter and check whether it's valid, and do all kinds of stuff such as fetching additional information from a database or another server.

We'll use it to validate our image name for now:

app.param("image", (req, res, next, image) => {    if (!image.match(/\.(png|jpg)$/i)) {        return res.status(req.method == "POST" ? 403 : 404).end();    }    req.image     = image;    req.localpath = path.join(__dirname, "uploads", req.image);    return next();});

We start by checking whether the name matches ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required