Reputation: 4820
I have a html page, which contains table of images, and in order to load each image I'm using JS:
<img id="imageId">
$("#imageId").attr("src", srcLink); // where srcLink = '/images/20180918_124058.jpg'
so for each image, I need to have a specific handle, like:
app.get('/images/20180918_124058.jpg', function (req, res) {
res.sendFile("/images/20180918_124058.jpg", {root: __dirname });
})
Is there option on the server (Node.JS) to handle all the dozen requests in one request (and parse the src link and send the right image back) ?
Upvotes: 1
Views: 41
Reputation: 708026
Is there option on the server (Node.JS) to handle all the dozen requests in one request (and parse the src link and send the right image back) ?
Yes, there is. You can create one route for all the images:
app.get('/images/:id', function (req, res, next) {
res.sendFile(path.join("/images", req.params.id), {root: __dirname }, function(err) {
if (err) return next(err);
});
});
Or, you could use express.static()
and have it serve the images for you from your /images
directory:
app.use("/images", express.static(path.join(__dirname, "images"), {fallthrough: false}));
Note: both of these options will serve any matching URL/filename found in the /images
directory so you need to make sure that there are ONLY files in that directory that you intend to be publicly available.
Upvotes: 2