W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
以下是在Node.js中創(chuàng)建Web應用程序的主要核心網(wǎng)絡模塊:
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服務器。
在每個客戶端請求,回調(diào)傳遞兩個參數(shù) - 傳入請求流和傳出服務器響應流。
要啟動返回的HTTP服務器,請調(diào)用其在端口號中傳遞的listen函數(shù)。
下面的代碼提供了一個簡單的服務器,監(jiān)聽端口3000,并簡單地返回“hello client!” 每個HTTP請求
var http = require("http");
//from m.o2fo.com
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/");
要測試服務器,只需使用Node.js啟動服務器。
$ node 1raw.js Server running at http://127.0.0.1:3000/
然后在新窗口中使用curl測試HTTP連接。
$ curl http://127.0.0.1:3000 hello client!
要退出服務器,只需在服務器啟動的窗口中按Ctrl + C。
curl發(fā)送的請求包含幾個重要的HTTP標頭。
為了看到這些,讓我們修改服務器以記錄在客戶端請求中接收的頭。
var http = require("http");
//m.o2fo.com
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)在啟動服務器。
我們將要求curl使用-i選項注銷服務器響應頭。
$ 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']訪問任何標頭。
默認情況下,狀態(tài)代碼為200 OK。
只要標頭未發(fā)送,你就可以使用statusCode響應成員設置狀態(tài)代碼。
response.statusCode = 404;
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: