Node.js之创建应用

1.使用Node.js时,不仅仅在实现一个应用,同时实现了整个HTTP服务器;

2.Node.js由下列几部分组成:

(1)引入required模块:我们可以使用require指令来载入Node.js模块

**使用require指令载入http模块,并将实例化的HTTP赋值给变量http:

var http=require("http")

(2)创建服务器:服务器可以监听客户端的请求,类似于Apache,Ningx等HTTP服务器;

**使用http.createServer()方法创建服务器,并使用listen方法绑定8888端口,函数通过request,response参数接收和响应数据;

var http=require("http")

http.createServer(function (request,response){

  response.writeHead(200,{'Content-Type':'text/plain'}); 

   //发送HTTP头部,HTTP状态值:200:OK

  //内容类型:text/plain

  response.end('Hello World ');        //发送响应数据"Hello World"

}).listen(8888);

console.log('Server running at http://127.0.0.1:8888/');

(3)接收请求与响应请求:服务器很容易创建,客户端可以使用浏览器或终端发送HTTP请求,服务器接收请求后返回响应数据;

原文地址:https://www.cnblogs.com/hqutcy/p/6236233.html