nodejs的http模塊方法怎么使用

這篇文章主要講解了“nodejs的http模塊方法怎么使用”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“nodejs的http模塊方法怎么使用”吧!

成都地區(qū)優(yōu)秀IDC服務(wù)器托管提供商(創(chuàng)新互聯(lián)建站).為客戶提供專業(yè)的資陽主機(jī)托管,四川各地服務(wù)器托管,資陽主機(jī)托管、多線服務(wù)器托管.托管咨詢專線:13518219792

nodejs http模塊的方法有:1、createServer(),可創(chuàng)造服務(wù)器實(shí)例;2、listen(),啟動服務(wù)器監(jiān)聽指定端口;3、setHeader();4、write();5、end();6、get();7、request()等。

nodejs的http模塊方法怎么使用

本教程操作環(huán)境:windows7系統(tǒng)、nodejs 12.19.0版,DELL G3電腦。

http模塊

1 基本用法

1.1 模塊屬性

1.1.1 HTTP請求的屬性

  • headers:HTTP請求的頭信息。

  • url:請求的路徑。

1.2 模塊方法

1.2.1 http模塊的方法

createServer(callback):創(chuàng)造服務(wù)器實(shí)例。

1.2.2 服務(wù)器實(shí)例的方法

listen(port):啟動服務(wù)器監(jiān)聽指定端口。

1.2.3 HTTP回應(yīng)的方法

  • setHeader(key, value):指定HTTP頭信息。

  • write(str):指定HTTP回應(yīng)的內(nèi)容。

  • end():發(fā)送HTTP回應(yīng)。

1.3 處理GET請求

Http模塊主要用于搭建HTTP服務(wù)。使用Node.js搭建HTTP服務(wù)器非常簡單。

var http = require('http');

http.createServer(function (request, response){
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8080, "127.0.0.1");

console.log('Server running on port 8080.');
  • 上面代碼第一行var http = require("http"),表示加載http模塊

  • 然后,調(diào)用http模塊的createServer方法,創(chuàng)造一個服務(wù)器實(shí)例,將它賦給變量http。

  • ceateServer方法接受一個函數(shù)作為參數(shù),該函數(shù)的request參數(shù)是一個對象,表示客戶端的HTTP請求

  • response參數(shù)也是一個對象,表示服務(wù)器端的HTTP回應(yīng)。response.writeHead方法表示,服務(wù)器端回應(yīng)一個HTTP頭信息;response.end方法表示,服務(wù)器端回應(yīng)的具體內(nèi)容,以及回應(yīng)完成后關(guān)閉本次對話

  • 最后的listen(8080)表示啟動服務(wù)器實(shí)例,監(jiān)聽本機(jī)的8080端口
    將上面這幾行代碼保存成文件app.js,然后用node調(diào)用這個文件,服務(wù)器就開始運(yùn)行了。

$ node app.js

這時命令行窗口將顯示一行提示“Server running at port 8080.”。打開瀏覽器,訪問http://localhost:8080,網(wǎng)頁顯示“Hello world!”。
上面的例子是當(dāng)場生成網(wǎng)頁,也可以事前寫好網(wǎng)頁,存在文件中,然后利用fs模塊讀取網(wǎng)頁文件,將其返回。

var http = require('http');
var fs = require('fs');

http.createServer(function (request, response){
  fs.readFile('data.txt', function readData(err, data) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end(data);
  });
}).listen(8080, "127.0.0.1");

console.log('Server running on port 8080.');

下面的修改則是根據(jù)不同網(wǎng)址的請求,顯示不同的內(nèi)容,已經(jīng)相當(dāng)于做出一個網(wǎng)站的雛形了。

var http = require("http");
http.createServer(function(req, res) {
  // 主頁
  if (req.url == "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Welcome to the homepage!");
  }
	// About頁面
  else if (req.url == "/about") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Welcome to the about page!");
  }
  // 404錯誤
  else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("404 error! File not found.");
  }
}).listen(8080, "localhost");

回調(diào)函數(shù)的req(request)對象,擁有以下屬性。

  • url:發(fā)出請求的網(wǎng)址

  • method:HTTP請求的方法

  • headers:HTTP請求的所有HTTP頭信息。

1.4 處理POST請求

當(dāng)客戶端采用POST方法發(fā)送數(shù)據(jù)時,服務(wù)器端可以對dataend兩個事件,設(shè)立監(jiān)聽函數(shù)。

var http = require('http');

http.createServer(function (req, res) {
  var content = "";

  req.on('data', function (chunk) {
    content += chunk;
  });

  req.on('end', function () {
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.write("You've sent: " + content);
    res.end();
  });

}).listen(8080);

data事件會在數(shù)據(jù)接收過程中,每收到一段數(shù)據(jù)就觸發(fā)一次,接收到的數(shù)據(jù)被傳入回調(diào)函數(shù)。end事件則是在所有數(shù)據(jù)接收完成后觸發(fā)。
對上面代碼稍加修改,就可以做出文件上傳的功能。

"use strict";

var http = require('http');
var fs = require('fs');
var destinationFile, fileSize, uploadedBytes;

http.createServer(function (request, response) {
  response.writeHead(200);
  destinationFile = fs.createWriteStream("destination.md");
  request.pipe(destinationFile);
  fileSize = request.headers['content-length'];
  uploadedBytes = 0;

  request.on('data', function (d) {
    uploadedBytes += d.length;
    var p = (uploadedBytes / fileSize) * 100;
    response.write("Uploading " + parseInt(p, 0) + " %\n");
  });

  request.on('end', function () {
    response.end("File Upload Complete");
  });
}).listen(3030, function () {
  console.log("server started");
});

2 發(fā)出請求

2.1 get()

get方法用于發(fā)出get請求。

function getTestPersonaLoginCredentials(callback) {
  return http.get({
    host: 'personatestuser.org',
    path: '/email'
  }, function(response) {
    var body = '';

    response.on('data', function(d) {
      body += d;
    });

    response.on('end', function() {
      var parsed = JSON.parse(body);
      callback({
        email: parsed.email,
        password: parsed.pass
      });
    });
  });
},

2.2 request()

request方法用于發(fā)出HTTP請求,它的使用格式如下。

http.request(options[, callback])

request方法的options參數(shù),可以是一個對象,也可以是一個字符串。如果是字符串,就表示這是一個URL,Node內(nèi)部就會自動調(diào)用url.parse(),處理這個參數(shù)。
options對象可以設(shè)置如下屬性

  • host:HTTP請求所發(fā)往的域名或者IP地址,默認(rèn)是localhost

  • hostname:該屬性會被url.parse()解析,優(yōu)先級高于host。

  • port:遠(yuǎn)程服務(wù)器的端口,默認(rèn)是80。

  • localAddress:本地網(wǎng)絡(luò)接口。

  • socketPath:Unix網(wǎng)絡(luò)套接字,格式為host:port或者socketPath。

  • method:指定HTTP請求的方法,格式為字符串,默認(rèn)為GET。

  • path:指定HTTP請求的路徑,默認(rèn)為根路徑(/)??梢栽谶@個屬性里面,指定查詢字符串,比如/index.html?page=12。如果這個屬性里面包含非法字符(比如空格),就會拋出一個錯誤。

  • headers:一個對象,包含了HTTP請求的頭信息。

  • auth:一個代表HTTP基本認(rèn)證的字符串user:password。

  • agent:控制緩存行為,如果HTTP請求使用了agent,則HTTP請求默認(rèn)為Connection: keep-alive,它的可能值如下:

    • undefined(默認(rèn)):對當(dāng)前host和port,使用全局Agent。

    • Agent:一個對象,會傳入agent屬性。

    • false:不緩存連接,默認(rèn)HTTP請求為Connection: close。

  • keepAlive:一個布爾值,表示是否保留socket供未來其他請求使用,默認(rèn)等于false。

  • keepAliveMsecs:一個整數(shù),當(dāng)使用KeepAlive的時候,設(shè)置多久發(fā)送一個TCP KeepAlive包,使得連接不要被關(guān)閉。默認(rèn)等于1000,只有keepAlive設(shè)為true的時候,該設(shè)置才有意義。
    request方法的callback參數(shù)是可選的,在response事件發(fā)生時觸發(fā),而且只觸發(fā)一次。
    http.request()返回一個http.ClientRequest類的實(shí)例。它是一個可寫數(shù)據(jù)流,如果你想通過POST方法發(fā)送一個文件,可以將文件寫入這個ClientRequest對象。
    下面是發(fā)送POST請求的一個例子。

var postData = querystring.stringify({
  'msg' : 'Hello World!'
});

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write(postData);
req.end();

注意,上面代碼中,req.end()必須被調(diào)用,即使沒有在請求體內(nèi)寫入任何數(shù)據(jù),也必須調(diào)用。因?yàn)?code>這表示已經(jīng)完成HTTP請求。
發(fā)送過程的任何錯誤(DNS錯誤、TCP錯誤、HTTP解析錯誤),都會在request對象上觸發(fā)error事件。

3 搭建HTTPs服務(wù)器

搭建HTTPs服務(wù)器需要有SSL證書。對于向公眾提供服務(wù)的網(wǎng)站,SSL證書需要向證書頒發(fā)機(jī)構(gòu)購買;對于自用的網(wǎng)站,可以自制。
自制SSL證書需要OpenSSL,具體命令如下。

openssl genrsa -out key.pem
openssl req -new -key key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
rm csr.pem

上面的命令生成兩個文件:ert.pem(證書文件)key.pem(私鑰文件)。有了這兩個文件,就可以運(yùn)行HTTPs服務(wù)器了。
Node.js提供一個https模塊,專門用于處理加密訪問。

var https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

var a = https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

上面代碼顯示,HTTPs服務(wù)器與HTTP服務(wù)器的最大區(qū)別,就是createServer方法多了一個options參數(shù)。運(yùn)行以后,就可以測試是否能夠正常訪問。

curl -k https://localhost:8000

感謝各位的閱讀,以上就是“nodejs的http模塊方法怎么使用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對nodejs的http模塊方法怎么使用這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

標(biāo)題名稱:nodejs的http模塊方法怎么使用
當(dāng)前路徑:http://muchs.cn/article34/gdehse.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計微信小程序外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、網(wǎng)站收錄靜態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司