[Node.js]web模块

摘要

什么是web服务器?

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

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

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

使用Node创建web服务器

Node.js 提供了 http 模块,http 模块主要用于搭建 HTTP 服务端和客户端。引入http模块

//引入http模块
var http=require("http");

创建web服务器

创建server.js文件,内容如下:

//引入http模块
var http=require("http");
//引入fs模块
var fs=require("fs");
//引入url模块
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);
            //http 状态码 404 not found 
            response.writeHead(404,{"Content-Type":"text/html"});        
        }else{
            response.writeHead(200,{"Content-Type":"text/html"});
            //响应文件内容
            response.write(data.toString());
        };
        response.end();
    });
}).listen(5544);
console.log("Server running at http://127.0.0.1:5544");

启动调试

因为在访问/时,因为在服务器上找不到该文件而报错,在浏览器响应的状态码为404

web服务器

浏览器

接下来,我们创建一个名称为index.html的页面,内容如下:

<html>
    <head>
        <title>My first page.</title>
    </head>
    <body>
        <h1>Hello my page world.  </h1>
    </body>
</html>

启动server,浏览http://127.0.0.1:5544/index.html

通过Node创建web客户端

创建client.js,代码如下:

var http=require("http");
//用于请求的选项
var options={
    host:"127.0.0.1",
    port:'5544',
    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.createClient(options,callback);
req.end();

输出

资料

http://www.runoob.com/nodejs/nodejs-web-module.html

原文地址:https://www.cnblogs.com/wolf-sun/p/6846728.html