node.js应用程序由以下三部分组成
1>导入所需模块:使用require指令来加载node.js模块
2>建立服务器:服务器能够监听客户端请求,相似于apache、nginx等
3>接收请求与响应请求:接收客户端/浏览器发送过来的请求,将处理获得的数据返回
以下是第一个例子html
//步骤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.");
控制台消息
浏览器请求以下
node