使用 Node 创建 Web 服务器
什么是 Web 服务器?
Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。
大多数 web 服务器都支持服务端的脚本语言(php、python、ruby)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。
目前最主流的三个Web服务器是Apache、Nginx、IIS。
Node.js 提供了 http 模块,http 模块主要用于搭建 HTTP 服务端和客户端,使用 HTTP 服务器或客户端功能必须调用 http 模块,代码如下:
- var http = require('http');
在通常的服务器中,数据流通的方式是客户先通过浏览器进行发送请求,服务器在项目中进行查找,然后进客户所需要的页面进行返回,在查找的过程中可能存在两种情况,就是存在和不存在,当然,我们会做出判断,下面就是简单的服务器实现过程:
1、编写服务器代码server.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);
-
-
- response.writeHead(404,{'Content-Type': 'text/html'});
- }
- else {
-
-
- 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/');
通过上面代码,我们就能够实现服务器对于文件的查找,下面,我们就进行创建一个html文件,然后通过浏览器进行访问
2、编写html文件(index.html),用于浏览器进行请求
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>index</title>
- </head>
- <body>
- 这是一个用于进行nodejs服务器测试的html文件,我们能够通过在浏览器上面输入
- http://127.0.0.1:8081/WebServer/index.html进行访问
- </body>
- </html>
创建完之后,我们进行测试,现在我的目录结构是这样的:
3、进行测试
(1) 首先我们启动服务器,使用命令node WebServer/server.js
(2) 在浏览器进行访问,在url栏中输入http://127.0.0.1:8081/WebServer/index.html
其显示效果如下所示:
后台效果如下所示:
当然,我们也能够通过访问通过http://127.0.0.1:8081/LoveYou.html访问server.js文件夹外边的文件
使用 Node 创建 Web 客户端
Node 创建 Web 客户端需要引入 http 模块,创建 client.js 文件,代码如下所示:
- var http = require('http');
-
- var options = {
- host: 'localhost',
- port: '8081',
- path: '/WebServer/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();
新打开终端,运行程序如下所示: