Im trying to access json data from a local server
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