[node] Node.js的Web 模块

[node] Node.js的Web 模块

  • [什么是 Web 服务器?](#什么是 Web 服务器?)
  • Web的应用架构
  • http
    • 使用方式
    • [使用 Node 创建 Web 服务器](#使用 Node 创建 Web 服务器)
    • [使用 Node 创建 Web 客户端](#使用 Node 创建 Web 客户端)

什么是 Web 服务器?

Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。

大多数 web 服务器都支持服务端的脚本语言(php、python、ruby)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。

目前最主流的三个Web服务器是Apache、Nginx、IIS。

Web的应用架构

  • Client - 客户端,一般指浏览器,浏览器可以通过 HTTP 协议向服务器请求数据。
  • Server - 服务端,一般指 Web 服务器,可以接收客户端请求,并向客户端发送响应数据。
  • Business - 业务层, 通过 Web 服务器处理应用程序,如与数据库交互,逻辑运算,调用外部程序等。
  • Data - 数据层,一般由数据库组成。

http

Node.js 提供了 http 模块,http 模块主要用于搭建 HTTP 服务端和客户端,处理与 web 服务器的交互等相关功能,使用 HTTP 服务器或客户端功能必须调用 http 模块

使用方式

js 复制代码
var http = require('http');

使用 Node 创建 Web 服务器

以下是一个最基本的 HTTP 服务器架构(使用 8080 端口)实例:

创建 index.html 文件:

html 复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>兼容性提示页面</title>
</head>
<body>
    <h1>兼容性提示</h1>
</body>
</html>

创建 server.js 文件:

js 复制代码
var http = require('http');
var fs = require('fs');
var url = require('url');

// 创建服务器
http.createServer( function (request, response) {  
   // 解析请求,包括文件名
   var pathname = url.parse(request.url).pathname;
   // 输出请求的文件名
   console.log("Request for " + pathname + " received.");
   // 从文件系统中读取请求的文件内容
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         // HTTP 状态码: 404 : NOT FOUND
         // Content Type: text/html
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{             
         // HTTP 状态码: 200 : OK
         // Content Type: text/html
         response.writeHead(200, {'Content-Type': 'text/html'});    
         // 响应文件内容
         response.write(data.toString());        
      }
      //  发送响应数据
      response.end();
   });   
}).listen(8081);
 
// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8081/');

终端启动服务:

复制代码
$node main.js
//输出
//Server running at http://127.0.0.1:8081/

浏览器端访问http://127.0.0.1:8081/index.html,打开后是index.html的内容展示,服务器终端会打印Request for /index.html received.,表明接受到了请求

注意,这里index.html文件需要在node执行命令所在的文件夹,否则会报找不到index.html文件错误;如果index.html文件改名为test.html,则访问http://127.0.0.1:8081/test.html可以正常查看,所以对访问文件名没有要求,只要与设置命名一致即可

使用 Node 创建 Web 客户端

创建 client.js 文件:

js 复制代码
var http = require('http');
// 用于请求的选项
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.html'  
};
// 处理响应的回调函数
var callback = function(response){
   // 不断更新数据
   var body = '';
   response.on('data', function(data) {
      body += data;
   });
   response.on('end', function() {
      // 数据接收完成
      console.log(body);
   });
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();

此时另外打开一个终端执行 node main.js,不要在同一个终端执行,否则服务端会终止,此时终端会打印index.html的内容,也即客户端接收到了服务端的所有数据

相关推荐
小粉粉hhh11 小时前
Node.js(三)——模块化
node.js
晓杰'12 小时前
从0到1实现 Balatro 游戏后端(1):项目规划与牌型判断实现
后端·websocket·typescript·node.js·游戏开发·项目实战·nestjs
@PHARAOH12 小时前
WHAT - npm和corepack
前端·npm·node.js
MPGWJPMTJT12 小时前
从 Volta 迁移到 mise:Windows 下 Node 版本管理切换记录
前端·node.js
zhangfeng113312 小时前
Remotion 渲染视频脚本 ,自动化编辑视频 Node.js 层面是“单线程 JS”,但在实际渲染时是“高度并行”的。
node.js·自动化·音视频
羽师14 小时前
Node.js和npx关系
node.js
灵魂学者14 小时前
使用 Electron 打包项目构建 .EXE 桌面应用程序(简)
electron·node.js·vue·build·桌面应用程序
右耳朵猫AI14 小时前
Node.js技术周刊 2026年第14周
node.js
gogoing1 天前
Node.js 模块查找策略(require 完整流程)
javascript·node.js
zhangfeng11331 天前
小龙虾 wordbuddy 安装浏览器控制器 agent-browser npm install -g agent-browse
前端·人工智能·npm·node.js