I am trying to create routing for a static site however placing readFile() in an if statement causes infinite loading in my browser and content doesn't load. I'm trying to do this without the use of Express or any similar framework.
Here is my code:
var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var server = http.createServer((req, res) => {
let parsedURL = url.parse(req.url, true);
let fPath = parsedURL.path;
if (fPath === "/") {
fPath = "/index.html";
}
file = path.join(__dirname, "/public" fPath);
if (fPath === "/index.html") {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err);
res.end("An error has occured.");
} else {
res.end(data);
}
});
} else if (fPath === "/information.html") {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err);
res.end("An error has occured.");
} else {
res.end(data);
}
});
}
});
server.listen(8000);
CodePudding user response:
If if (fPath === "/index.html") {
matches and fs.readFile
has an error, then you don't send a response.
The same is true for "/information.html"
.
And if fPath
isn't either of those then you get to the end and you don't send a response.
The endless loading is caused by the browser waiting for a response you never send.
You need to make sure that every path through your if
statements calls res.end
or another function that sends a response to the browser.