简体   繁体   中英

How to create a node.js server?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM