node.js应用程序由如下三部分组成
1>导入所需模块:使用require指令来加载node.js模块
2>创建服务器:服务器可以监听客户端请求,类似于apache、nginx等
3>接收请求与响应请求:接收客户端/浏览器发送过来的请求,将处理得到的数据返回
如下是第一个例子
//步骤1:导入所需模块 //这里我们使用require指令来载入http模块,并将实例化的HTPP赋值给变量http var http = require('http'); //步骤2:创建服务器 //这里我们使用http.createServer()创建服务器 //并使用listen方法绑定3000端口 //通过request、response参数来接收和响应数据 http.createServer(function(request, response) { //响应状态:200;内容类型:text/html response.writeHead(200 , {"Content-Type":"text/html"}); //响应内容 response.write("<h1>Node.js</h1>"); //响应结束 response.end("<p>Hello World</p>"); //端口号:3000 }).listen(3000); //控制台打印出信息 console.log("HTTP server is listening at port 3000.");
控制台消息

浏览器请求如下
