node.js建立server

Node.js 組成:javascript

一、required模塊:使用require指令來載入Node.js模塊;java

二、建立服務器:服務器用於監聽客服端的請求,相似於apache等http服務器。node

三、接收請求與響應請求:客戶端使用瀏覽器或終端發送http請求,服務器接收請求後返回響應數據。apache

建立 Node.js 第一個 "Hello, World!" 應用。瀏覽器

  1. 引入required模塊
    1. 使用require指令載入http模塊,將實例化的http賦值給http:
    2. var http = require('http');

       

  2. 建立服務器
    1. http.createServer()方法建立服務器;該函數返回一個對象,該對象具備一個叫listen的方法;
    2. listen方法綁定8888端口; 指定http服務器監聽的端口號;
    3. 函數經過request和response參數來接收和響應數據;
    4. 建立一個server.js的文件完成一個能夠工做的http服務器,代碼以下:
    5. var http = require('http');
      http.createServer(function(request,response){
          //發送http頭部
          //http狀態值:200:ok
          //內容類型:text/plain  (plain顯示代碼段)
          response.writeHead(200,{'Content-Type':'text/plain'});
      
          //發送響應數據「hello world」
          response.end('hello world');
      }).listen(8888);
      
      //終端打印信息
      console.log('Server running at http://127.0.0.1:8888/');

       

    6. node命令執行上面的代碼:服務器

    7. node server.js
      Server running at http://127.0.0.1:8888/

    8. 使用瀏覽器訪問http://127.0.0.1:8888/ 瀏覽器將輸入‘hello world’;函數

                  

相關文章
相關標籤/搜索