Node.js HTTP

2018-02-16 19:26 更新

以下是在Node.js中創(chuàng)建Web應(yīng)用程序的主要核心網(wǎng)絡(luò)模塊:

net / require("net")            the foundation for creating TCP server and clients 
dgram / require("dgram")        functionality for creating UDP / Datagram sockets 
http / require("http")          a high-performing foundation for an HTTP stack 
https / require("https")        an API for creating TLS / SSL clients and servers 

http模塊有一個函數(shù)createServer,它接受一個回調(diào)并返回一個HTTP服務(wù)器。

在每個客戶端請求,回調(diào)傳遞兩個參數(shù) - 傳入請求流和傳出服務(wù)器響應(yīng)流。

要啟動返回的HTTP服務(wù)器,請調(diào)用其在端口號中傳遞的listen函數(shù)。

例子

下面的代碼提供了一個簡單的服務(wù)器,監(jiān)聽端口3000,并簡單地返回“hello client!” 每個HTTP請求

var http = require("http"); 
//from m.hgci.cn
var server = http.createServer(function (request, response) { 
    console.log("request starting...");
     // respond 
    response.write("hello client!"); 
    response.end(); 
}); 
server.listen(3000); 
console.log("Server running at http://127.0.0.1:3000/"); 

要測試服務(wù)器,只需使用Node.js啟動服務(wù)器。

$ node 1raw.js 
Server running at http://127.0.0.1:3000/ 

然后在新窗口中使用curl測試HTTP連接。

$ curl http://127.0.0.1:3000 
hello client! 

要退出服務(wù)器,只需在服務(wù)器啟動的窗口中按Ctrl + C。

檢查接頭

curl發(fā)送的請求包含幾個重要的HTTP標(biāo)頭。

為了看到這些,讓我們修改服務(wù)器以記錄在客戶端請求中接收的頭。

var http = require("http"); 
//m.hgci.cn
var server = http.createServer(function (req, res) { 
    console.log("request headers..."); 
    console.log(req.headers);
     // respond 
    res.write("hello client!"); 
    res.end(); 
}).listen(3000); 
console.log("server running on port 3000"); 

現(xiàn)在啟動服務(wù)器。

我們將要求curl使用-i選項注銷服務(wù)器響應(yīng)頭。

$ curl http://127.0.0.1:3000 -i 
HTTP/1.1 200 OK 
Date: Thu, 22 May 2014 11:57:28 GMT 
Connection: keep-alive 
Transfer-Encoding: chunked 

hello client! 

如你所見,req.headers是一個簡單的JavaScript對象字面量。你可以使用req ['header-name']訪問任何標(biāo)頭。

設(shè)置狀態(tài)代碼

默認(rèn)情況下,狀態(tài)代碼為200 OK。

只要標(biāo)頭未發(fā)送,你就可以使用statusCode響應(yīng)成員設(shè)置狀態(tài)代碼。

response.statusCode = 404; 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號