国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

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模塊有一個(gè)函數(shù)createServer,它接受一個(gè)回調(diào)并返回一個(gè)HTTP服務(wù)器。

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

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

例子

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

var http = require("http"); 
//from eska-fuses.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/"); 

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

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

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

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

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

檢查接頭

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

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

var http = require("http"); 
//eska-fuses.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)在啟動(dòng)服務(wù)器。

我們將要求curl使用-i選項(xiàng)注銷(xiāo)服務(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! 

如你所見(jiàn),req.headers是一個(gè)簡(jiǎn)單的JavaScript對(duì)象字面量。你可以使用req ['header-name']訪問(wèn)任何標(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)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)