[关闭]
@xiu-tanwy 2016-11-10T02:42:12.000000Z 字数 1626 阅读 297

Node.js Web 模块

node


什么是 Web 服务器?

Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,
Web服务器的基本功能就是提供Web信息浏览服务。
它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。
大多数 web 服务器都支持服务端的脚本语言(php、python、ruby)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。

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

cmd-markdown-logo

使用 Node 创建 Web 服务器

Node.js 提供了 http 模块,http 模块主要用于搭建 HTTP 服务端和客户端,使用 HTTP 服务器或客户端功能必须调用 http 模块,代码如下:

  1. var http = require('http');
  2. var fs = require('fs');
  3. var url = require('url');
  4. // 创建服务器
  5. http.createServer( function (request, response) {
  6. // 解析请求,包括文件名
  7. var pathname = url.parse(request.url).pathname;
  8. // 输出请求的文件名
  9. console.log("Request for " + pathname + " received.");
  10. // 从文件系统中读取请求的文件内容
  11. fs.readFile(pathname.substr(1), function (err, data) {
  12. if (err) {
  13. console.log(err);
  14. // HTTP 状态码: 404 : NOT FOUND
  15. // Content Type: text/plain
  16. response.writeHead(404, {'Content-Type': 'text/html'});
  17. }else{
  18. // HTTP 状态码: 200 : OK
  19. // Content Type: text/plain
  20. response.writeHead(200, {'Content-Type': 'text/html'});
  21. // 响应文件内容
  22. response.write(data.toString());
  23. }
  24. // 发送响应数据
  25. response.end();
  26. });
  27. }).listen(8081);
  28. // 控制台会输出以下信息
  29. console.log('Server running at http://127.0.0.1:8081/');

接下来我们在该目录下创建一个 index.htm 文件,代码如下:

  1. <html>
  2. <head>
  3. <title>Sample Page</title>
  4. </head>
  5. <body>
  6. Hello World!
  7. </body>
  8. </html>

执行 server.js 文件:

使用 Node 创建 Web 客户端

Node 创建 Web 客户端需要引入 http 模块,创建 client.js 文件,代码如下所示:

  1. var http = require('http');
  2. // 用于请求的选项
  3. var options = {
  4. host: 'localhost',
  5. port: '8081',
  6. path: '/index.htm'
  7. };
  8. // 处理响应的回调函数
  9. var callback = function(response){
  10. // 不断更新数据
  11. var body = '';
  12. response.on('data', function(data) {
  13. body += data;
  14. });
  15. response.on('end', function() {
  16. // 数据接收完成
  17. console.log(body);
  18. });
  19. }
  20. // 向服务端发送请求
  21. var req = http.request(options, callback);
  22. req.end();
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注