I have created a simple http server using http module. On receipt of GET request with correct url, first the HTML file is being read and stored in a variable using fs.readFileSync() method and then it is being written to the response body and sent along with the response. But in this case the favicon is not loaded with the page.
Note: I am using Visual Studio Code.
const http = require("http");
const fs = require("fs");
const server = http.createServer(serverFunc);
server.listen(3000, () => console.log("Server is running at <http://localhost:3000/>"));
function serverFunc(req, res){
switch(req.method){
case "GET":
responseFunc();
break;
case "POST":
case "PUT":
case "DELETE":
default:
res.statusCode = 405;
res.statusMessage = "Method Not Allowed";
res.setHeader("Content-Type", "text/plain");
res.end("Not Allowed");
break;
}
function responseFunc(){
if(req.url === "/"){
res.statusCode = 202;
res.statusMessage ="OK";
res.setHeader("Content-Type", "text/html");
res.setHeader("charset", "UTF-8");
let html = fs.readFileSync("index.html");
res.write(html);
res.end();
}else{
res.statusCode = 404;
res.statusMessage ="Not Found";
res.setHeader("Content-Type", "text/plain");
res.end("Page Not Found!");
}
}
}
Expected page load with favicon but favicon is not loading.