Node.js 搭建Web服务器和Web客户端
2023-09-11 14:22:55 时间
服务器定义
Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。
目前最主流的三个Web服务器是Apache、Nginx、IIS。
Web 应用架构
1. Client - 客户端,一般指浏览器,浏览器可以通过 HTTP 协议向服务器请求数据。
2. Server - 服务端,一般指 Web 服务器,可以接收客户端请求,并向客户端发送响应数据。
3. Business - 业务层, 通过 Web 服务器处理应用程序,如与数据库交互,逻辑运算,调用外部程序等。
4. Data - 数据层,一般由数据库组成。
文档目录结构
代码实战
1、htmlDemo.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
http.createServer(function(request, response) {
var pathname = url.parse(request.url).pathname;
var readDir = path.join(__dirname, 'public');
//默认路径是命令行的路径,而不是js文件的路径
//不仅是html文件,所用到的资源(image、css、js等)都会在该函数被请求
//html里的图片不能访问到它的上一级目录
console.log('Request for pathname = ' + pathname);
var subPathname = pathname.substr(1);
if(!subPathname) {
subPathname = 'index.html';
}
if(!path.extname(subPathname)) {
subPathname+='.html';
}
console.log('after modify pathname = ' + subPathname);
var readPath = path.join(readDir, subPathname);
console.log(readPath);
fs.readFile(readPath, function(err, data) {
if(!err) {
response.writeHead(200, {'Content-Type':'text/html'});
response.end(data);
} else {
console.log(err);
response.writeHead(404, {'Content-Type':'text/html'});
fs.readFile(path.join(readDir, '404.html'), function(err, data) {
if(err) {
console.log(err);
response.end();
} else {
response.end(data);
}
});
}
});
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080');
http.request({host:'localhost', port:'8080', path:'/index.html'}, function(response){
//注意这里必须先赋空值,否则会加入'undefined'字符串
var body = '';
//一直有数据,需要不断的更新
response.on('data', function(data){
//调用多少次response.write和end就会触发多少次on('data')事件
console.log('response.on data emitter');
body += data;
}).on('end', function(){
console.log('response.on end emitter');
console.log(body);
});
}).end();
2、index.html
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
3、404.html
<html>
<head>
<title>404 File Not Found</title>
</head>
<body>
<img src="images/404.jpg" width="100%" height="100%" />
</body>
</html>
运行截图
相关文章
- Node.js: Python not found exception due to node-sass and node-gyp
- js_html_input中autocomplete="off"在chrom中失效的解决办法 使用JS模拟锚点跳转 js如何获取url参数 C#模拟httpwebrequest请求_向服务器模拟cookie发送 实习期学到的技术(一) LinqPad的变量比较功能 ASP.NET EF 使用LinqPad 快速学习Linq
- 文字无缝滚动jQuery上下滚动js效果代码
- js获取URL地址参数
- JS基础 DOM
- JS利用window对象改变局部变量的作用域(改为全局变量)
- Node.js(五)—— 内置模块之net模块和http模块
- Node.js创建服务器
- js数据结构-链表
- js函数的调用问题
- js怎么获取图片的相对地址
- 【HarmonyOS】【JS】鸿蒙Js camera怎么拍照并使用image显示出来
- Node.js创建自签名的HTTPS服务器
- vue引入外部js数据
- Node.js机制及原理理解初步
- jQuery插件之验证控件jquery.validate.js
- PHP实现无符号右移(js中的 >>>)
- 原生JS实现bind()函数
- Node.js:Buffer(缓冲区)介绍及常用方法
- D3.js系列——动态效果和Update、Enter、Exit的理解
- Windows系统完全卸载删除 Node.js
- 使用node.js + express框架 搭建一个微型服务器
- js获取页面名称和路径参数