Node.js Web模块
Node.js Web模块
参考https://www.runoob.com/nodejs/nodejs-web-module.html
什么是Web服务器
- Web服务器一般指提供Web信息浏览服务的某种类型的计算机程序,一般支持HTTP协议、HTML文档格式和URL,需要与客户端的浏览器等配合使用;
- 大多数Web服务器都支持服务端的脚本语言(PHP、python、ruby等),并通过这些脚本语言从数据库中获取数据,将结果返回给客户端;
- 目前最主流的三个web服务器是Apache、Nginx、IIS。
web应用架构
- Client:客户端,一般指浏览器,通过HTTP协议向服务器请求数据。
- Server:服务端:一般指Web服务器,可以接收客户端的请求,并向客户端发送响应数据。
- Business:业务层:通过web服务器处理应用程序,如与数据库交互、逻辑运算、调用外部程序等。
- Data:数据层,一般由数据库组成。
通过Node.js创建web服务器
使用http模块搭建HTTP服务端和客户端。
var http = require('http');
例如:
var http = require('http');
var fs = require('fs');
var url = require('url');
// 创建HTTP服务器
http.createServer((req, res)=>{
// 解析请求,包括文件名
var pathname = url.parse(req.url).pathname;
// 输出请求的文件名
console.log("Request for: "+pathname+"Received.");
// 从文件系统中读出请求的文件内容
fs.readFile(pathname.substr(1), ((err, data)=>{
if(err){
console.log(err);
res.writeHead(404, {'Content-Type':'text/html'});
}else{
res.writeHead(200, {'Content-Type':'text/html'});
res.write(data.toString);
}
res.end();
}));
}).listen(8080);
console.log("Server running at http://127.0.0.1:8080/");
然后同级目录下创建一个index.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>标题</h1>
<p>段落</p>
</body>
</html>
然后浏览器输入:
http://127.0.0.1:8080/index.html
结果:
使用Node.js创建web客户端
还是需要引入http模块,写在另一个文件client.js中:
var http = require('http');
// 用于请求的选项
var options = {
host: 'localhost',
port: '8080',
path: '/index.html'
};
// 处理响应的回调函数
var callback = function(response){
// 不断更新数据
var body = "";
response.on('data', (data)=>{
body += data;
});
response.on('end', ()=>{
// 数据接收完成
console.log(body);
});
};
var req = http.request(options, callback);
req.end();
或者简化一下结构:
require('http').request({host:'localhost',port:'8080',path:'/index.html'}, (response)=>{
// 不断更新数据
var body = "";
response.on('data', (data)=>{
body += data;
});
response.on('end', ()=>{
// 数据接收完成
console.log(body);
});
}).end();
在另一个终端执行client.js,控制台输出:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>标题</h1>
<p>段落</p>
</body>
</html>