Bài 13: NodeJS – Web Module – NodeJS cơ bản

Trang chủ » Training » Bài 13: NodeJS – Web Module – NodeJS cơ bản
01/03/2022 Training 88 viewed

Web Server là gì?

Web Server là một ứng dụng phần mềm có thể xử lý các HTTP request được gửi bởi HTTP Client (ví dụ: trình duyệt web) và trả về một trang web trong phản hồi tới Client. Web Server thường gửi các tài liệu html bên cạnh các ảnh cũng như style sheet và các đoạn Javascript.

Cấu trúc ứng dụng Web

Một ứng dụng web thường được chia thành 4 lớp như sau:
Client – Lớp này bao gồm các trình duyệt web và các ứng dụng có thể tạo ra các HTTP request đến Web Server.
Server – Lớp này bao gồm các Web Server có thể can thiệp các request được tạo bởi Client và trả về các phản hồi (response).
Business – Lớp này bao gồm ứng dụng trên Server có thể được tận dụng bởi các Web Server để thực hiện các tiến trình xử lý cần thiết. Lớp này tương tác với lớp Data qua các chương trình bên ngoài.
Data – Lớp này bao gồm các Database và bất kì các nguồn dữ liệu nào.

Tạo Web Server bởi sử dụng Node.js

Node.js cung cấp http Module có thể được sử dụng để tạo các HTTP client và server. Dưới đây là phần kiến trúc thu nhỏ của HTTP Server được lắng nghe trên cổng 8081.
Đầu tiên, bạn tạo server.js có nội dung như sau:
var http = require('http');
var fs = require('fs');
var url = require('url');

// Create a server
http.createServer( function (request, response) {  
   // Parse the request containing file name
   var pathname = url.parse(request.url).pathname;
   
   // Print the name of the file for which request is made.
   console.log("Request for " + pathname + " received.");
   
   // Read the requested file content from file system
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         
         // HTTP Status: 404 : NOT FOUND
         // Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      } else {	
         //Page found	  
         // HTTP Status: 200 : OK
         // Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});	
         
         // Write the content of the file to response body
         response.write(data.toString());		
      }
      
      // Send the response body 
      response.end();
   });   
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
Bây giờ tạo index.htm cùng thư mục với server.js:
<html>
   <head>
      <title>Sample Page</title>
   </head>
   
   <body>
      Hello World!
   </body>
</html>
Chạy server.js để xem kết quả:
$ node server.js
Kiểm tra kết quả
Server running at http://127.0.0.1:8081/
Tạo Request tới Node.js Server
Mở http://127.0.0.1:8081/index.htm trong bất kỳ trình duyệt nào và xem kết quả.
Kiểm tra kết quả:
Server running at http://127.0.0.1:8081/
Request for /index.htm received.

Tạo Web Client bởi sử dụng Node.js

Để tạo Web Client, bạn cũng có thể sử dụng http Module. Dưới đây là ví dụ minh họa.
Tạo client.js có nội dung sau:
var http = require('http');

// Options to be used by request 
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};

// Callback function is used to deal with response
var callback = function(response) {
   // Continuously update stream with data
   var body = '';
   response.on('data', function(data) {
      body += data;
   });
   
   response.on('end', function() {
      // Data received completely.
      console.log(body);
   });
}
// Make a request to the server
var req = http.request(options, callback);
req.end();
Chạy client.js trên một màn hình Terminal khác để xem kết quả:
$ node client.js
Kiểm tra kết quả:
<html>
   <head>
      <title>Sample Page</title>
   </head>
   
   <body>
      Hello World!
   </body>
</html>
Tiếp đó kiểm tra kết quả trên Server.
Server running at http://127.0.0.1:8081/
Request for /index.htm received.
Chia sẻ:
Tags:
TOP HOME