Reputation: 3051
currently on my server I have under the path theses images:
/opt/myproject/assets/5259521.jpg
/opt/myproject/assets/5259522.jpg
/opt/myproject/assets/5259523.jpg
I am using nodejs to create my web services. I want to know what is the way to return the path of my images so that the front-end can show them in an img
tag.
my restAPI can be accessed by a path:
Here I would need to return the image paths so that I can display them in my web application.
app.use(cors());
app.options('*', cors());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json());
// Configuración global de rutas
app.use(require('./routes/index'));
const distDirectory = path.join(__dirname, '/public');
app.get('*', function (req, res, next) {
const file_path = path.join(distDirectory, req.url.split('?').shift());
if (fs.existsSync(file_path)) next();
else res.sendFile(path.join(distDirectory, 'index.html'));
});
app.use(express.static(distDirectory));
thanks
Upvotes: 2
Views: 233
Reputation: 384
To use the static files in Node js
There is a path called 'public' which holds all the files CSS, Bootstrap, Images etc.
add this line to the code
app.use(express.static("public")
if the structure of public folder is
-public -css -picture -images
then you have use images for frontend
<img src = "picture/a.png">
<img src = "image/b.png">
<img src = "image/c.png">
you can have many folders in public folder
Upvotes: 0
Reputation: 10569
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
You need to put all you images in public
folder or add the folder name of you choice and then pass the static folder in the express.static
middleware.
The name of the folder Public
is just a convention, you can set name of folder to anything.
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:
app.use(express.static('public'))
And access it like :
http://localhost:3000/assets/5259521.jpg
I am assuming that you the images are under public/assets
folder.
Upvotes: 1