我爱编程

node.js web 模块

2018-03-30  本文已影响0人  飞鱼_JS

什么是 Web 服务器?

Web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。

大多数 web 服务器都支持服务端的脚本语言(php、python、ruby)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。

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

Web 应用架构

image.png

node 创建服务端

const http =require('http');
const fs = require('fs');
const url = require('url');
http.createServer((req,res)=>{
    let pathname = url.parse(req.url).pathname;
    console.log('requset for'+pathname+'received');
    fs.readFile(pathname.substr(1),(err,data)=>{
        if(err){
            console.log("readFile err",err)
            res.writeHead(404,{'Content-Type':'text/html;charset=utf-8'});
        }else{
            res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})
            res.write(data.toString())
        }
        res.end()
    })
}).listen(8000);
console.log("Server is running at 127.0.0.1:8080");

node 创建客户端

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() {
      // 数据接收完成
      console.log(body);
   });
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();
上一篇 下一篇

猜你喜欢

热点阅读