Onur Tuna Onur Tuna - 1 month ago 11
Apache Configuration Question

localhost:8080 is not loaded for Node.js on Mac OS X

I'm following a tutorial for Node.js and i have the code below:

var http = require("http");

http.createServer(function (request, response){
request.on("end", function() {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);


I have saved that code as http.js. When I try to check localhost:8080 nothing happens, only waiting. However, when I try entering localhost I see dummy "It works!" message. Probably something is running in my computer too. How can I get rid of it? I have tried stopping apache and deleting everything in /Library/WebServer/Documents.

Oxi Oxi
Answer
const http = require('http');

http.createServer( function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(8080);

Thats a simple http server in nodeJS.

"It works!" is the default index.html of successful installed/Running Apache http server, by default which runs on port 80. and your nodejs server is listening on port 8080, so there there is no problem and both can co-exist.

by any chance if you still want to stop apache server

sudo service apache2 stop

can be used.

and if there is any server running on port 8080, and then you try to start your http server on port 8080, you will receive Error: listen EADDRINUSE if, your server starts without this error, you can be sure that, nothing else is running on port 8080

EDIT: request.on(end) is fired when the request from client(browser) ends. but in your case browser is still waiting for your response and the request is pending. as soon as you call response.end(), immediately, the request.on(end) will be triggered.

now i will modify your code, to work this way, with small modification

var http = require("http");

http.createServer(function (request, response){
        response.end('Hello HTTP!');  //change
        request.on("end", function() {
                //should be outside or removed
                /*response.writeHead(200, {
                        'Content-Type': 'text/plain'
                });*/

        });
}).listen(8080);