2

I'm trying to create my first node.js server and I have some problems.

When I use

var http = require("http");

var server = http.createServer();
server.listen(8888);

No connection can be established to the server.

But when I use this

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

The server lands ok.

I used this in a file called server.js and runned the command node server.js. I'm using v 0.12.0 What am I missing? Why the server doesn't work on the first case?

1
  • you could add event listener server.on('connect', function (request, socket, head) { console.log('someone connected'); }); and this should be the same as passing function to createServer() Commented Oct 1, 2015 at 10:31

1 Answer 1

6

The first block of code creates a server and listens on a port.

When you point a browser at it, the browser makes a request and then waits for a response.

You haven't told the server what to respond with, so it sits there doing nothing.

Eventually the browser times out.

In the second set of code, you've told the server how to respond to requests.

Sign up to request clarification or add additional context in comments.

6 Comments

So if I say console.log('Test'); in the server.js file it should work? Cause I made that and it's not working.
When I add console.log('Test'); to the end of the first script, it gets output on my console when I run the program.
So it does work. Telling Node to output something to the console is not the same as telling it how to respond to an HTTP request.
So getting to what am I missing. What I now understand is that with node you need to tell him to make an HTTP request on the server, when with Apache not? Is this correct?
When you are writing an HTTP server using Node, you have to tell it how to respond to a request. When you are using Apache, that is an HTTP server that someone else has written for you, and it has been written so that if you haven't told it how to respond to a request, it will respond with a 404 error page.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.