node --第一個應用

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

相關文章
相關標籤/搜索