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

152
Visualizações
Fetch request returns html/text instead of JSON content when launched from Nodejs server

I am launching a html webpage in my NodeJS server. On running the server.js file, it basically writes json data to a file, then launches the Nodejs server after 3 seconds (so the HTML file has enough time to fetch the written data) as shown below.

setTimeout(() => {
  const server = http.createServer((req, res) => {
    res.writeHead(200, { "content-type": "text/html" });
    fs.createReadStream("index.html").pipe(res);
  });
  server.listen(3000);
  console.log(`Server is running on http://localhost:3000/`);
}, 3000);

But, when I fetch the sites.json file, the content received is HTML code in the network tab.

    <script>
        fetch('sites.json')
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                appendData(data);
                console.log(data)
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });
        function appendData(data) {
            var mainContainer = document.getElementById("myData");
            for (var i = 0; i < data.length; i++) {
                var div = document.createElement("div");
                div.innerHTML = 'Name: ' + data[i];
                mainContainer.appendChild(div);
            }
        }
    </script>

I tried to make http request and it worked, therefore the problem only occurs when I try to fetch json files locally.

I am not sure if this is the proper way to host a http server since it's my first time attempting this.

about 4 years ago · Santiago Gelvez
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