Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
errorTypeError: Cannot read properties of undefined (reading 'map')

I'm trying to use Strapi Headless CMS to create blog posts. I managed to fetch the JSON data but I'm unable to display it as HTML using the map() function. I want to display this data into the HTML but I keep getting this error. I already tried with a for loop and foreach() but I keep getting the same error like this or errorTypeError: Cannot read properties of undefined (reading 'data'). Here's my code so far:

 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);
});

The JSON file looks like this:

{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"
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try to replace this line:

body.innerHTML = `${post.data.data[0].attributes.body}`;

with:

body.innerHTML = `${post.data[0].attributes.body}`;
about 4 years ago · Juan Pablo Isaza Relatório

0

TypeError: Cannot read properties of undefined (reading 'data')

As error says, It is not able to read the data property as you are having only one data object in the response.

Valid JSON :

{
    "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"
        }
    }]
}

Hence, access it by calling data[0].attributes.body instead of data.data[0].attributes.body.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda