关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

Node.js Web 模块

发布时间:2020-03-14 00:00:00

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

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

 

使用node创建服务器

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

演示一个最基本的 HTTP 服务器架构(使用 8080 端口)

创建 main.js 文件

var http=require("http");var fs=require("fs");var url=require("url");//创建服务器http.createServer(function(req,res){//解析请求的文件名var pathname=url.parse(req.url).pathname;//被请求的文件已收到请求console.log("被请求的文件"+pathname+"已收到请求");//读取文件内容  //pathname.substr(1) 去掉.fs.readFile(pathname.substr(1),function(err,data){if(err){
            console.log(err);
            res.writeHead(404,{"Content-Type":"text/html"});// HTTP 状态码: 404 : NOT FOUND}else{          
            res.writeHead(200,{"Content-Type":"text/html"});// HTTP 状态码: 200 : OK            res.write(data.toString());
        }
        res.end();
    })
}).listen(8080);

console.log("Server running at http://127.0.0.1:8080/");

该目录下创建一个 index.html 文件

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>indextitle>head><body><h1>标题h1><p>段落p>body>html>

 

 在浏览器中打开地址:http://127.0.0.1:8080/index.html

 

 

 

 

使用node创建web客户端

client.js

var http=require("http");//用于请求的选项var options={
   host:"localhost",
   port:"8080",
   path:"/index.html" };//处理响应的回调函数var callback=function(res){var body="";
    res.on("data",function(data){
        body+=data;
    })
    res.on("end",function(){
        console.log(body);
    })
}//向服务器发送请求var req=http.request(options,callback);
req.end();

 

 (我把前面服务器文件main.js改为了server.js)

然后新开一个终端,运行client.js

 

 

再回来看第一个终端

 

 

成功~


/template/Home/Zkeys/PC/Static