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.