nodeJs編寫的簡單服務器


 

 一、簡單的nodeJs寫的 http 服務器

1.先Hello world,創建最簡單的 Node 服務器(server.js)

var http = require("http");

http.createServer(function(request, reponse) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

執行: 

node server.js

1. var http = require("http")  表示請求NodeJs自帶的 http 模塊,並賦值給 http 變量

2.  http.createServer()  會返回一個對象,這個對象有一個 listen 方法,這個方法有一個Number類型的參數,該參數指定了HTTP服務器監聽的端口號

3. 所以本段代碼 會開啟一個監聽 8888 端口的服務器,我們可以通過打開瀏覽器,訪問 http://localhost:8888/  來連接該服務器,我們會看到網頁上寫着 “Hello World”

 

二、事件驅動和回調:

上面的代碼也可以如此編寫:(即onRequest函數作為參數傳遞給 http.createServer() 

var http = require("http");
function onRequest(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");

onRequest函數會在 http.createServer() 方法執行時的特定時間點去調用(即某個事件發生時,才會執行——事件驅動的回調

回調函數的目的: 當我們使用 http.createServer 方法的時候,我們當然不只是想要一個偵聽某個端口的服務器,我們還想要它在服務器收到一個HTTP請求的時候做點什么

執行上面的代碼(node server.js )終端會輸出上圖的  Server has started.  文本;

再打開 http://localhost:8888/  路徑,終端會輸出上圖的 Request received. 文本,輸出兩次(因為還會訪問一次http://localhost:8888/favicon.ico);

這就是事件驅動,訪問時(事件發生)才會調用。

 

三、服務器相關:

1. onRequest函數被調用時,request 和 response 作為參數會被傳入;

2. request 和 response 是對象,可以使用它們的方法來 處理HTTP請求的細節,也可以 響應請求 (即給發請求的瀏覽器返回數據);

3. 上面的代碼:

收到請求時,

使用 response.writeHead() 函數發送一個HTTP狀態(200)和HTTP頭的內容類型(content-type),

使用 response.write() 函數在HTTP相應主體中發送文本“Hello World"。

調用 response.end() 完成響應。

 暫時未使用 request ,request中放的是請求時的攜帶的參數

 

四、node中模塊的導入導出

//導入http模塊,並使用
var http = require("http");
...
http.createServer(...).listen(8888);
//此處使用http變量來接受賦值,也可以使用其他變量


//導出自己的模塊start,我們把它寫在server.js中
function start() {
   ...   
}

exports.start = start;

//導入自己的模塊start
var server = require("./server");

server.start();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM