I am trying to setup a template site using Node.JS. I am new to using Node.JS and am trying to open up an HTML file and a CSS file before continuing towards the rest of the code. However, even upon reaching reponse.end(), the loop continues to run, and in fact goes for a second time, but does not make it to the end again. I threw in some console.log()s in order to demonstrate this. I will throw both my JS code and mode console output down below. I do not know how to fix this, and any help would be appreciated. Thank you all very much!
const server = require('http').createServer()
const markdown = require( "markdown" ).markdown
const fs = require('fs')
server.on('request', (request, response) => {
response.setHeader('Content-Type', 'text/html')
var page = fs.readFileSync("html/tb.html", 'utf8')
console.log("reading html...")
page = "<style>" fs.readFileSync("css/style.css", 'utf8') "</style>"
console.log("reading css...")
const lang = Intl.DateTimeFormat().resolvedOptions().locale
if (request.url === '/') {
response.end()
}
else if (request.url === '/coucou') {
page =markdown.toHTML('#Hello world!')
response.end(page)
console.log("end")
}
})
server.listen(4000)
I am sorry for my lack of NodeJS experience, but I could not seem to find an answer to this question anywhere else. Here is my console output when loading 'coucou':
reading html...
reading css...
end
reading html...
reading css...
And here it is on the homepage
reading html...
reading css...
reading html...
reading css...
It does not continue after the second round, but the browser never receives an end signal, and therefore continues to load indefinitely. How do I get it to actually process the end of the response and to tell my browser to stop loading?
Again, thank you all very much!!!
CodePudding user response:
I tried changing the response.end()s in the if-else blocks to response.write() and put one single response.end() following the conditional block like so.
if (request.url === '/') {
response.write(page)
}
else if (request.url === '/coucou') {
page =markdown.toHTML('#Hello world!')
response.write(page)
console.log("end")
}
response.end()
That seemed to have done the trick!! Thank you all very much in any case!
CodePudding user response:
Add the following to your script:
if (request.url === '/') {
response.end()
} else if (request.url === '/coucou') {
page =markdown.toHTML('#Hello world!')
response.end(page)
console.log("end")
} else {
console.log("No response for " request.url);
}
The log output should explain what's happening: there's a third case in which you never were ending the response.
A look in the network panel of your browser's devtools will also show you which request is still hanging without a complete response.
It's most likely the favicon that a browser requests by default. The page content will have loaded, but the status bar will still show "loading". As @jfriend suggests, use
response.status(404).end();
in theelse
block