How to fetch images from node.js server's folder in URL? How to fetch images from node.js server's folder in URL? express express

How to fetch images from node.js server's folder in URL?


It's like you have already set your data/img folder as a static folder in the line below:

app.use(express.static('data/img'));

In that case, you should be accessing images placed in the static folder above using below url:

http://localhost:3000/default.jpg

I will however advice you use Node's global variable __dirname to indicate the root of the static folder but this depends on where your server.js is located within your file structure.

The js file containing the snippets below is located in the root and I have /data/img folder from the root as well and I am able to retrieve the image using /image name.

var express = require('express');var app = express();app.use(express.static(__dirname + '/data/img'));app.listen(3500, function () {    console.log('Express server is listening, use this url - localhost:3500/default.png');});

See if this helps you. If it does, make sure you know the reason for using the __dirname global variable name.

SO1