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

131
Visualizações
[Node.js]Access json file in another folder with file.readFile

Im trying to access json data from a local server

  • js(folder)
    • item_data.json
    • server.js
    • client.js
  • index.html

In my client.js

var xhttp
window.onload = function(){
  requestData("http://localhost:8000/js/item_data.json");
}

function requestData(URL){
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = processData;
  xhttp.open("GET", URL, true);
  console.log(xhttp);  //it prints information with status: 0
}

function processData(){
  console.log(xhttp.status); //prints 0
  if(xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) { // do something }
  else{ console.log("ERROR"); } //This is always printed
}

In my server.js

const http = require("http");
const file = require("fs");
const host = "localhost";
const port = 8000;

const server = http.createServer(processRequest);

function processRequest(request, response){
  if(request.url === "/index.html"){
    file.readFile('../index.html', 'utf8', function(err, contents) {
      if(err){
        response.writeHead(500, { "Content-Type": "text/html"});
        response.end();
        return;
      }
      response.writeHead(200, { "Content-Type": "text/html"});
      response.end(contents);
  });
  else if(request.url === "/js/item_data.json"){
    file.readFile('item_data.json', 'utf8', function(err, contents) {
        if(err){
          response.writeHead(500, { "Content-Type": "application/javascript"});
          response.end();
          return;
        }
        response.writeHead(200, { "Content-Type": "application/javascript"});
        response.end(contents);
    });
  }
}

I have tried to change the content type to application/json
Tried to use /js/item_data.json
And request.url === "/item_data.json"
They both not working

about 4 years ago · Juan Pablo Isaza
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