Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJS Can only connect when Server is shutdown

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading