I’m stuck and seriously confused why this is not working and no error is displayed in console.
Im using JavaScript and nodejs and express
i have created an Api endpoint, and i have test it on Postman and it gives me the URL of the image
// API endpoint to get product images by product ID
app.get('/api/product-images/:productID', (req, res) => {
const { productID } = req.params;
const sql = "SELECT ImageURL FROM productimages WHERE ProductID = ?";
db.query(sql, [productID], (err, results) => {
if (err) {
console.error('Error fetching images:', err);
return res.status(500).send('Error retrieving images');
}
res.json(results);
});
});
and here is the fetch on client side code
function fetchProductImages(productID) {
console.log(`Fetching images for product ID: ${productID}`);
fetch(`http://localhost:3000/api/product-images/${productID}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP status ${response.status}: ${response.statusText}`);
}
return response.json();
})
.then(image => {
console.log("Received images:", image); // Check the structure and content
console.log('images:', image);
const imagesContainer = document.getElementById('imagesContainer');
console.log('Container:', imagesContainer); // Check if the container is being correctly identified
if (!imagesContainer) {
console.error('Images container not found');
return;
}
if (image.length === 0) {
console.log('No images to display');
imagesContainer.innerHTML = '<p>No images available.</p>';
} else {
imagesContainer.innerHTML = ''; // Clear previous content
image.forEach(image => {
console.log('Adding image:', image.ImageURL);
const imgElement = document.createElement('img');
imgElement.src = image.ImageURL;
imgElement.className = 'rounded m-1';
imgElement.alt = 'Product Image';
imgElement.style.width = '200px'; // Set width via style attribute
imagesContainer.appendChild(imgElement);
});
}
})
.catch(error => {
console.error('Error loading images:', error);
document.getElementById('imagesContainer').innerHTML = `<p>Error loading images: ${error.message}</p>`;
});
}
and here is the HTML part
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header align-items-center d-flex justify-content-between">
<h4 class="card-title mb-0 flex-grow-1">Product Images</h4>
</div>
<div class="card-body">
<div class="live-preview">
<div id="imagesContainer" class="row align-items-center">
<!-- Images will be dynamically inserted here -->
</div>
</div>
</div>
</div>
</div>
</div>
no images is displayed