Код: Выделить всё
{
"id": 21,
"address": "example 1",
"price": 4,
"images": [
{
"id": 2,
"url": "/uploads/chicago_background_70fff5f0ee.jpg"
},
{
"id": 1,
"url": "/uploads/property_showcase_6363007fdf.png"
}
]
}
< /code>
Я могу получить доступ к изображениям напрямую через URL -адреса, такие как:
http://localhost:1337/uploads/chicago_background_70fff5f0ee.jpg< /code> < /p>
Несмотря на правильный ответ API, журналы консоли показывают пустой массив изображений для свойства 21:
Property 21 Images: Array []
Код: Выделить всё
import React, { useEffect, useState } from "react";
import axios from "axios";
const CarouselSection = ({ title }) => {
const [properties, setProperties] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchProperties = async () => {
try {
const apiUrl = import.meta.env.VITE_API_URL;
console.log("API URL:", apiUrl);
const response = await axios.get(`${apiUrl}/api/properties?populate[images][fields][0]=url`);
console.log("Full Response:", response.data);
const propertiesData = response.data?.data || [];
if (!Array.isArray(propertiesData) || propertiesData.length === 0) {
throw new Error("No properties found or invalid response structure");
}
const parsedProperties = propertiesData.map((property) => {
const images =
Array.isArray(property.images) && property.images.length > 0
? property.images.map((image) => `${apiUrl}${image.url.startsWith('/') ? image.url : `/${image.url}`}`)
: [];
console.log(`Images for property ID: ${property.id} URLs:`, images);
return {
id: property.id,
address: property.address || "No Address Available",
price: property.price !== null ? `$${property.price}` : "N/A",
bedrooms: property.bedrooms || 0,
bathrooms: property.bathrooms || 0,
sqft: property.sqft || 0,
listingstatus: property.listingstatus || "Unknown",
zillowlink: property.zillowlink || "#",
images,
};
});
setProperties(parsedProperties);
} catch (err) {
setError("Failed to fetch property data");
console.error("Error fetching properties:", err.response ? err.response.data : err.message);
} finally {
setLoading(false);
}
};
fetchProperties();
}, []);
if (loading) return Loading...
;
if (!properties.length) return
No properties available
;
return (
{title}
{properties.map((property) => (
{property.images && property.images.length > 0 ? (
{property.images.map((src, index) => (
[img]{src} alt={`Property ${property.id} Image ${index + 1}`} /[/img]
))}
) : (
No images available
)}
{property.address}
{property.price}
))}
);
};
export default CarouselSection;
< /code>
Выпуск: < /h3>
[*] Ответ API бэкэнд содержит допустимые URL -адреса изображения, и они доступны в браузере напрямую. /li>
Однако при извлечении данных в приложении React Property.Images
среда: < /h3>
[*] Frontend: React с Vite < /li>
Бэкэнд: strapi (работает локально по адресу http: // localhost: 1337 )
URL -адрес базы API: vite_api_url = http: // localhost: 80
< /ul>
Почему изображения не обрабатываются правильно в фронте, даже если ответ API -версии действителен? < /h3>
Как может Я исправляю это так, чтобы изображения отображались, как и ожидалось на фронте?
Подробнее здесь: https://stackoverflow.com/questions/794 ... ct-app-str