M thaker M thaker -4 years ago 138
Node.js Question

can not read image from folder in node.js

I have put images inside "/public/images" path. Now in the respose I am getting url as I wanted. But as soon as I paste that url to web browser, it says Cannot GET /public/images/food-1-xxhdpi.png. So should I write separate API to handle that?

Main file app.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
var PORT = 3000;
var foodtrucklist = require('./controller/foodtrucklist.js');
var foodtruck = require('./model/datafoodtruck');

var db = mongoose.connect('mongodb://127.0.0.1:27017/quflip');

mongoose.connection.once('connected', function() {
console.log("Connected to database")
foodtruck.save(function(err,foodtrucks){
if (err) res.send(err);
});
});

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public/images'));


app.get('/foodtrucklist',foodtrucklist);

app.listen(PORT,function() {
console.log('express listining on port' + PORT);
});

Answer Source

This line

app.use(express.static(__dirname + '/public/images'));

Maps the static content in the /public/images folder to the root of your web application. So the request /public/images/food-1-xxhdpi.png will only work if the full path is .../public/images/public/images/food-1-xxhdpi.png

You should either make your request for /food-1-xxhdpi.png or change the line of code to something like:

 app.use('/my-virtual-directory',express.static(__dirname + '/public/images'));

so that requests can be picked up in what ever you choose to make /my-virtual-directory

So... Your file in this case becomes /my-virtual-directory/food-1-xxhdpi.png

Obviously, you can still do this to make it map externally to the same way you have it internally with:

 app.use('/public/images', express.static(__dirname + '/public/images'));

Here is more info on the static middleware for express: https://expressjs.com/en/starter/static-files.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download