I have a local express server that serves a json file. I also have many image files inside a local folder. The image paths are parts of the json object which I want to show in my DOM. However I get string representation of these image paths as part of response which I can't use. What is the best way to server local images to the frontend from a local server.
My server side config:
app.use(express.static(path.join(__dirname, 'public'))) app.use(express.static(path.join(__dirname, 'server/img')))
My JSON file
{ "Images": [{ "title": "First Block", "images": ["server/img/bijay.jpg", "server/img/dance.png", "server/img/ocean.jpg"] }, {obj2}, {obj3}, {obj4}] }
My client-side code to print image
<ul> <li ng-repeat="obj in objArray"><img ng-src="{{obj.images[0]}}"></li> </ul> // just testing first image
My folder structure:
Images are inside the img folder. not shown here to save space
Finally after a lot of rethinking, I found the solution.
I had defined the 'static' folder in the server as 'server/img'. However, inside the json object, I was assigning the absolute path for the image files again. All I needed to do was ' server/image/ imgFileName.jpg' to resolve the conflict :))
Based on the comments of @Tolsee:
Place the images in a 'public' folder. (/public/img/dance.png) Then in your express app add the following line:
let app = express();
app.use(express.static(path.join(__dirname, 'public')));
The images will be available with the following url:
localhost:port/img/dance.png
You could just serve /server/img and then just use the following:
let app = express();
app.use(express.static('/server/img'));
localhost:port/dance.png
Some configuration might be needed depending on your project structure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.