Estoy tratando de usar Strapi Headless CMS para crear publicaciones de blog. Logré obtener los datos JSON pero no puedo mostrarlos como HTML usando la función map(). Quiero mostrar estos datos en el HTML pero sigo recibiendo este error. Ya probé con un bucle for y foreach() pero sigo recibiendo el mismo error como este o errorTypeError: Cannot read properties of undefined (reading 'data'). Aquí está mi código hasta ahora:
const blogPosts = "http://localhost:1337/api/blogposts"; fetch(blogPosts) .then((response) => { return response.json(); }) .then((data) => console.log(data.data[0].attributes)) .then((data) => { let posts = data; posts.map(function (post) { let body = document.createElement("div"); body.innerHTML = `${post.data.data[0].attributes.body}`; li.appendChild(body); }); }) .catch(function (err) { console.log("error" + err); });El archivo JSON se ve así:
{data: Array(1) data: Array(1) 0: attributes: body: "text" createdAt: "2022-02-11T10:29:48.930Z" publishedAt: "2022-02-11T10:29:58.780Z" updatedAt: "2022-02-11T10:29:58.790Z"Intenta reemplazar esta línea:
body.innerHTML = `${post.data.data[0].attributes.body}`;con:
body.innerHTML = `${post.data[0].attributes.body}`;TypeError: no se pueden leer las propiedades de undefined (leyendo 'datos')
Como dice el error, no puede leer la propiedad de data ya que solo tiene un objeto de data en la respuesta.
JSON válido:
{ "data": [{ "attributes": { "body": "text", "createdAt": "2022-02-11T10:29:48.930Z", "publishedAt": "2022-02-11T10:29:58.780Z", "updatedAt": "2022-02-11T10:29:58.790Z" } }] } Por lo tanto, acceda llamando a data[0].attributes.body .attributes.body en lugar de data.data[0].attributes.body .