W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
以下是在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)頭。
默認(rèn)情況下,狀態(tài)代碼為200 OK。
只要標(biāo)頭未發(fā)送,你就可以使用statusCode響應(yīng)成員設(shè)置狀態(tài)代碼。
response.statusCode = 404;
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: