前言
在 NodeJS 中用來創建服務的模塊是 http 核心模塊,本篇就來介紹關于使用 http 模塊搭建 HTTP 服務器和客戶端的方法,以及模塊的基本 API。
HTTP 服務器
1、創建 HTTP 服務器
在 NodeJS 中,創建 HTTP 服務器可以與 net 模塊創建 TCP 服務器對比,創建服務器有也兩種方式。
方式 1:
const http = require("http");const server = http.createServer(function(req, res) {  // ......});server.listen(3000);方式 2:
const http = require("http");const server = http.createServer();server.on("request", function(req, res) {  // ......});server.listen(3000);在 createServer 的回調和 request 事件的回調函數中有兩個參數,req(請求)、res(響應),基于 socket,這兩個對象都是 Duplex 類型的可讀可寫流。
http 模塊是基于 net 模塊實現的,所以 net 模塊原有的事件在 http 中依然存在。
const http = require("http");const server = http.createServer();// net 模塊事件server.on("connection", function(socket) {  console.log("連接成功");});server.listen(3000);2、獲取請求信息
在請求對象 req 中存在請求的方法、請求的 url(包含參數,即查詢字符串)、當前的 HTTP 協議版本和請求頭等信息。
const http = require("http");const server = http.createServer();server.on("request", function(req, res) {  console.log(req.method); // 獲取請求方法  console.log(req.url); // 獲取請求路徑(包含查詢字符串)  console.log(req.httpVersion); // 獲取 HTTP 協議版本  console.log(req.headers); // 獲取請求頭(對象)  // 獲取請求體的內容  let arr = [];  req.on("data", function(data) {    arr.push(data);  });  req.on("end", function() {    console.log(Buffer.concat(arr).toString());  });});server.listen(3000, function() {  console.log("server start 3000");});通過 req 對應的屬性可以拿到請求行和請求首部的信息,請求體內的內容通過流操作來獲取,其中 url 中存在多個有用的參數,我們自己處理會很麻煩,可以通過 NodeJS 的核心模塊 url 進行解析。
const url = require("url");let str = "http://user:pass@www.pandashen.com:8080/src/index.html?a=1&b=2#hash";// parse 方法幫助我們解析 url 路徑let obj = url.parse(str, true);console.log(obj);// {//   protocol: 'http:',//   slashes: true,//   auth: 'user:pas',//   host: 'www.pandashen.com:8080',//   port: '8080',//   hostname: 'www.pandashen.com',//   hash: '#hash',//   search: '?a=1&b=2',//   query: '{ a: '1', b: '2' }',//   pathname: '/src/index.html'//   path: '/src/index.html?a=1&b=2',//   href: 'http://user:pass@www.pandashen.com:8080/src/index.html?a=1&b=2#hash' }            
新聞熱點
疑難解答
圖片精選