Obtain the actual file path from a JSON response

I have set up a local express server to serve a JSON file, but I am facing an issue with displaying image files located in a local folder. The image paths are included in the JSON object that I want to display in my DOM. However, the response I receive includes string representations of these image paths, which cannot be used directly. What is the most effective way to serve local images from a local server to the frontend?

Visual representation of the problem:

Configuration on my server side:

app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'server/img')))

The structure of my JSON file:

{
  "Images": [{
    "title": "First Block",
    "images": ["server/img/bijay.jpg", "server/img/dance.png", "server/img/ocean.jpg"]
  }, {obj2}, {obj3}, {obj4}]
}

Client-side code for displaying images:

<ul>
  <li ng-repeat="obj in objArray"><img ng-src="{{obj.images[0]}}"></li>
</ul>
// testing the display of the first image only

Folder structure overview:

The images are stored within the img folder, which is not displayed here to keep the content concise.

Answer №1

After much contemplation, I was able to discover the answer at last.

I realized that I had incorrectly set the 'static' folder on the server as 'server/img'. The issue arose when I was assigning absolute paths for the image files within the JSON object. By simply correcting it to 'server/image/imgFileName.jpg', the conflict was resolved smoothly :))

Answer №2

After reviewing the feedback from @Tolsee:

First, ensure all images are placed within a designated 'public' folder. (e.g. /public/img/dance.png) Next, include the following code in your express application:

let app = express();
app.use(express.static(path.join(__dirname, 'public')));

Access the images using the corresponding URL:

localhost:port/img/dance.png

Alternatively, you can serve /server/img and utilize the following approach:

let app = express();
app.use(express.static('/server/img'));

localhost:port/dance.png

Adjustments may be necessary based on the structure of your project.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieving the file name from FormData following an Axios request

I have a question regarding extracting the file name of a WAV file in Node.js. I am sending the file to my backend through Axios using FormData, but I'm unsure how to retrieve the file name. Any assistance would be greatly appreciated. Frontend: //fi ...

Are ES6 arrow functions not supported in IE?

When testing this code in my AngularJs application, it runs smoothly on Firefox. However, when using IE11, a syntax error is thrown due to the arrows: myApp.run((EventTitle, moment) => { EventTitle.weekView = event => \`\${moment(event.s ...

JavaScript forEach functionality is not compatible with Dynamics CRM 2016

I'm currently working on writing some JavaScript code for a ribbon button in Dynamics CRM 2016 that will extract phone numbers from a list of Leads displayed in the Active Leads window. However, I've encountered an error message when attempting ...

Clicking on a jQuery element will reveal a list of corresponding elements

I've retrieved a list of elements from the database and displayed them in a table with a button: <a href="#" class="hiden"></a> To show and hide advanced information contained within: <div class="object></div> Here is my jQ ...

An alternative to Socket.io tailored for up-to-date web browsers

Are there any specialized versions of Socket.io or similar libraries that cater to modern browsers exclusively, utilizing Websockets without the need for legacy browser support and outdated code? ...

Sorting table by priority in HTML is not functioning as expected

I am currently developing this code for a SharePoint 2010 platform. While the table can currently be sorted alphabetically, I am looking to implement a different functionality. Unfortunately, I am facing an issue with changing variables 'a' and ...

How can you utilize a previously opened window from another page in JavaScript?

One of my challenges involves managing windows in a JavaScript environment. When I open a child window using window.open("http://foobar","name"), it reuses the same window when opened with the same name, which is exactly what I want. However, if the origi ...

Warning: The Unhandled Promise Rejection arises when an error is thrown within an asynchronous function without a try-catch block

Encountering the following issue in my Node-Express App UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error came about either by throwing inside an async function without a catch block, or rejecting a promise that was not hand ...

Troubleshooting a Laravel 5.2 modal popup issue for password recovery, experiencing a 500 internal server error with the Ajax function execution

Is there a way to check if an email exists in order to send a reset password link using an AJAX function? I keep encountering a 500 internal server error before the AJAX runs. I understand that a 500 error is usually due to a token mismatch, but do I actua ...

Load CKEditor.js with RequireJS following the textarea element

If you need a WYSIWYG editor, CKEditor could be the answer. Check out their documentation here. To properly load CKEditor, make sure to add the following script tag in the header: <script src="../ckeditor/ckeditor.js"></script> ... Then, inc ...

Steps for modifying an element in an array using Javascript

Currently, I am a beginner in the realm of JavaScript and I am trying to build a todo-style application. So far, I have successfully managed to create, display, and delete items from an array. However, I am facing challenges when it comes to editing these ...

How can I customize the visibility toggles for the password input field in Angular Material?

Currently immersed in the Angular 15 migration process... Today, I encountered an issue with a password input that displays two eyes the first time something is entered in the field. The HTML code for this is as follows: <mat-form-field appearance=&qu ...

Unlocking the power of promises: How Node.js excels at handling

I'm facing a situation where my controller code is structured like this. const Users = require("../models/users"); class UserController() { getUserById(req, res) { const id = req.params.id; const users = new Users(); ...

Testing an Express route using Mocha and Chai: A comprehensive guide

I am currently developing an express app that renders views with filtered data. Here is my current route: router.get('/user/name/:name', (req, res) => { return serverUtil.getUserByName(req.params.name).then(success =>{ res.ren ...

Guide to transmitting webcam feed from server to servlet

I am trying to display the webcam connected to my server in a servlet. I have come across suggestions to use getUserMedia();, however, this only captures the user's video webcam feed and not the server's. Is there a way to achieve this? My servl ...

PHP and JavaScript are two powerful programming languages that are

While I understand that PHP and JavaScript operate in different locations, I am curious to know if there is a way to incorporate some PHP code into my JavaScript file. I need to create unique URLs for linking to profiles and news posts, such as /#/news/IDH ...

Can anyone recommend a regular expression that would target values ranging from 0.5 to 24?

I'm searching for a regex pattern that can identify numbers within the range of 0.5 to 24, excluding cases like 0,5 or 22,5. The current pattern I'm using is: /^(([0-9]|1[0-9]|2[0-3])([^,])(\.(0|5)))$/ Despite having excluded the comma ,, ...

Exploring the functionality of Radar Chart within a React component

Within the index.html file that is being utilized, there exists a javascript code specifically designed for the chart function. <script src="js/plugins/chartJs/Chart.min.js"></script> var radarData = { labels: ["In Perso ...

Unconventional login processes showcased in Redux-Saga's documentation

When looking at the login flow example in the redux-saga documentation, it is clear that the expected action sequence is well-defined. However, does the LOGOUT action always follow the LOGIN action? In real-world scenarios, such as when a user's sessi ...

Include a new JSON object into an already populated JSON array

Can someone help me with updating a JSON array by adding a new object to it in an Android app? The JSON data is stored on a remote server and I am currently using GSON library for parsing it. Any assistance would be greatly appreciated. Thank you! ...