Nodejs Web模块

1.首先我们来了解一下什么是Web服务器

Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。

它只需支持HTTP协议,HTML文芳格式及URL,与客户端的网络浏览器配合。大多数web服务器都支持服务端的脚本语言(php,

python,ruby)等,并通过脚本语言获取数据,将结果返回给客户端浏览器

2.知道Web架构主要的四部分

1)Client--客户端,一般指浏览器,浏览器可以通过HTTP协议向服务器请求数据。

2)Server--服务器,一般指Web服务器,介意接收客户端的请求,并向客户端发送响应数据。

3)Business--业务层,通过Web服务器处理应用程序,如与数据库交互,逻辑运算,调用外部程序等。

4)Data--数据层,一般数据库组成。

4.了解之后  我们接下来使用Node创建Web服务器

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

var http = require('http');

接下来需要创建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);
         
         // Content Type: text/html
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{             

         // Content Type: text/html
         response.writeHead(200, {'Content-Type': 'text/html'});    
         
         // 响应文件内容
         response.write(data.toString());        
      }
      //  发送响应数据
      response.end();
   });   
}).listen(3000);

 然后我们建一个index.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ENN❤)</title>
</head>
<body>
    <h1>标题</h1>
    <p>段落。</p>
</body>
</html>

  做好之后 我们来看一下效果,打开地址http://127.0.0.1:3000/index.html

我们就做好了❤

原文地址:https://www.cnblogs.com/0428mm/p/12074141.html