Home > Net >  How to dynamically create routes in Node.js express. ex-- my.app.com/ghi5938
How to dynamically create routes in Node.js express. ex-- my.app.com/ghi5938

Time:03-20

In my webapp, I give users the ability to upload a photo. When that photo is uploaded to my server, I would like to dynamically create a route that they can click on and go view that image. Im not sure where to start looking into this and the few articles I found didnt seem to answer my question. How do I dynamically create new routes in node.js?

CodePudding user response:

Typically, you don't create new routes in Express once you've already initialized the server. Instead, you create a single route at the beginning with some sort of parameter to it. The parameter can either be part of the URL or part of the query string. Then, you have a single, pre-defined route that handle the URL with the parameter in it. The parameter varies per each request and the code in the single route uses the parameter to decide which content to send.

So, for your photo upload, you would accept the upload and then allocate that image some sort of unique imageID. That imageID will then put put in the URL to serve that specific image. If the imageID for a just-uploaded image was 123456789, then it could look like this:

// incoming URL path /image/xxxxxx
// where xxxxxx is the imageID
app.get("/image/:imageID", (req, res) => {
    let imageID = req.params.imageID;
    // in your server file system, find the image for imageID and build a path to it
    let imagePath = findImageID(imageID);
    if (imagePath) {
        res.sendFile(imagePath);
    } else {
        res.sendStatus(404);
    }
});

An imageID just needs to be something that you can lookup and turn into an actual image filepath. It's really up to you how you do it. It can be the actual filename of the image. It can be an ID you look up in your database where you store the path to the image. Or, you can invent some other scheme. There just needs to be a way to create the imageID when your image is uploaded and a way to implement findImageID(imageID) that gives you a path to the image from an imageID.

For fixed resources like images, I would prefer the scheme above where the imageID is part of the path since it really is part of the URL resource specification. But, technically, it could also be done with a query string:

// image?id=xxxxxxx
// where xxxxxx is the imageID
app.get("/image", (req, res) => {
    let imageID = req.query.id;
    // in your server file system, find the image for imageID and build a path to it
    let imagePath = findImageID(imageID);
    if (imagePath) {
        res.sendFile(imagePath);
    } else {
        res.sendStatus(404);
    }
});
  • Related