Node.js Web模块基础教程文档

收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體

Node.js Web模块

什么是Web服务器

Web服务器是处理HTTP客户端发送的HTTTP请求的软件程序例如网络浏览器,并返回网页以响应客户端。 Web服务器通常以html文档以及图像,样式表和脚本作为响应。
大多数Web服务器使用脚本语言来支持服务器端脚本,或者重定向到执行从数据库获取数据的特定任务的应用服务器。 ,执行复杂的逻辑等操作,然后通过Web服务器将结果发送到HTTP客户端。
Apache Web服务器是最常用的Web服务器之一。这是一个开源项目。

Web应用程序体系结构

Web应用程序可以分为4层:
客户端层: 客户端层包含可向Web服务器发出HTTP请求的Web浏览器,移动浏览器或应用程序。 服务器层: 服务器层包含Web服务器,可以拦截客户端发出的请求并将响应传递给他们。 业务层: 业务层包含应用服务器,Web服务器利用该服务器来执行所需的处理。该层通过数据库或某些外部程序与数据层进行交互。 数据层: 数据层包含数据库或任何数据源。 Node.js Web层

使用Node.js创建Web服务器

Node.js提供了http模块,可用于创建服务器的HTTP客户端。使用以下代码创建一个名为server.js的js文件:
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/');
接下来,在创建server.js的同一目录中创建一个名为index.html的html文件,其中包含以下代码
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
现在打开Node.js命令提示符并运行以下代码:
节点server.js
Node.js web module1
在任何浏览器中打开http://127.0.0.1:8081/index.htm,并看到以下结果。
Node.js网络模块2