Im trying out setting up a webserver with nodeJS with this code:
const http = require("http")
const port = 8080
const fs = require("fs")
const server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/html" })
fs.readFile("index.html", function (error, data) {
if (error) {
res.writeHead(404)
res.write("Error")
} else {
res.write(data)
}
res.end
})
})
server.listen(port, function (error) {
if (error) {
console.log("Something went wrong")
} else {
console.log("Server is listening on port " port)
}
})
But when I connect on any browser(tried chrome and mozilla) using either localhost or 127.0.0.1 the page will only show when I shut the server down. It's constantly loading, not showing anything until I shutdown with ctrl C. Then it will show my HTML page. Same problem was when I didnt use an html page and just responded with
res.write("hey")
CodePudding user response:
res.end
is a function, try res.end()
You had never ended the request so the browser has been waiting for it to end and it only happened when you closed the server.
CodePudding user response:
Because you just show the method
res.end
but not run it.