国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

NodeJS搭建HTTP服務器的實現步驟

2024-05-06 15:28:48
字體:
來源:轉載
供稿:網友

前言

在 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' }            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 郯城县| 涞源县| 龙胜| 延边| 建宁县| 平凉市| 尖扎县| 巨鹿县| 广德县| 封丘县| 绥阳县| 砀山县| 漯河市| 东山县| 郁南县| 汕头市| 海原县| 随州市| 分宜县| 九台市| 新营市| 江津市| 讷河市| 习水县| 宝应县| 巩留县| 兴业县| 甘洛县| 阿荣旗| 五常市| 绥化市| 田林县| 泗洪县| 高清| 荔波县| 辰溪县| 棋牌| 龙井市| 舒城县| 新密市| 大竹县|