Node构建Web服务器

Web模块

  • web服务器,网站服务器
  • 提供Web信息浏览服务;只支持HTTP协议、Html文档格式及URL,与客户端的网络浏览器配合
  • web服务器 = 服务端的脚本语言(php/ruby/python) + 从数据库获取数据 + 返回结果给客户浏览器
  • 最主流Web服务器 Apache/ Nginx/ IIS
  • Web应用架构
    • Client 客户端:浏览器
    • Server 服务端: Web服务器
    • Business 业务层: 与数据交互、逻辑运算、调用外部程序 (位于web服务器上的处理应用程序
    • Data 数据层:数据库

使用node构建一个服务端

  1. server.js //http服务器搭建
  2. router.js //路由模块
  3. index.js //松散添加路由
  1. server.js此处构建一个服务器,可在此扔入静态页面,就可以进行访问
var http = require('http');
var url = require('url');
var fs = require("fs");

function start(route){  
    function onRequest(request,response){
           // 解析请求,包括文件名
           var pathname = url.parse(request.url).pathname;
           
           // 输出请求的文件名
           console.log("Request for " + pathname + " received.");
           
           //路由调用
           route(pathname);
           
            // 从文件系统中读取请求的文件内容
           fs.readFile(pathname.substr(1), function (err, data) {
              if (err) {
                 console.log(err);
                 // HTTP 状态码: 404 : NOT FOUND
                 // Content Type: text/plain
                 response.writeHead(404, {'Content-Type': 'text/html'});
              }else{             
                 // HTTP 状态码: 200 : OK
                 // Content Type: text/plain
                 response.writeHead(200, {'Content-Type': 'text/html'});    
                 
                 // 响应文件内容
                 response.write(data.toString());        
              }
              //  发送响应数据
              response.end();
           });              
    }
    // 创建服务器
    http.createServer(onRequest).listen(8080);
     
    // 控制台会输出以下信息
    console.log('Server running at http://127.0.0.1:8080/');
}
exports.start = start;
  1. router.js :路由导航
function route(pathname){
  console.log("About to route a request for " + pathname);
}   
exports.route = route;
  1. index.js 路由服务注入服务器的控制文件
var server = require("./server");
var router = require("./router");
server.start(router.route);

此时server.js文件所在文件地址就是http://127.0.0.1:8080/
即http://127.0.0.1:8080/index.html就是指与server.js文件同地址下的index.html文件

使用node构建一个客户端

  1. client.js 相当于创建一个浏览器
var http = require('http');

//用于请求的选项
var options={
    host:'localhost',
    port:'8080',
    path:'/index.html'
}

//处理响应的回调函数
var callback = function(response){
    //不断更新数据
    var body = '';
    response.on('data',function(data){
        body += data;
    })
    response.on('end',function(){
        //数据接收完成
    })
}

//向服务端发送请求
var req = http.request(options,callback);
req.end();

你可能感兴趣的:(Node构建Web服务器)