为了账号安全,请及时绑定邮箱和手机立即绑定

无涯教程: Node.js - Web模块

标签:
Node.js

Web服务器是一个软件应用程序,它处理HTTP客户端(例如Web浏览器)发送的HTTP请求,并返回网页以响应客户端, Web服务器通常提供html文档以及图像,样式表和脚本。

Web应用架构

Web应用程序通常分为四层-

https://img1.sycdn.imooc.com/611f1fa00001820805340261.jpg

  • Client                - 该层由Web浏览器,移动浏览器或可以向Web服务器发出HTTP请求的应用程序组成。

  • Server               - 此层具有Web服务器,可以拦截客户端发出的请求并将响应传递给他们。

  • Business Layer  - 该层包含应用服务器,Web服务器利用该服务器来执行所需的处理。

  • Data Layer        - 此层包含数据库或任何其他数据源。

创建Web服务器

Node.js提供了一个 http 模块,该模块可用于创建服务器的HTTP客户端,以下是侦听8081端口的HTTP服务器的最基本结构。

创建一个名为server.js的js文件-

var http=require('http');
var fs=require('fs');
var url=require('url');
//Create a server
http.createServer( function (request, response) {  
   //Parse the request containing file name
   var pathname=url.parse(request.url).pathname;
   
   //Print the name of the file for which request is made.
   console.log("Request for " + pathname + " received.");
   
   //Read the requested file content from file system
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         
         //HTTP Status: 404 : NOT FOUND
         //Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      } else {	
         //Page found	  
         //HTTP Status: 200 : OK
         //Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});	
         
         //Write the content of the file to response body
         response.write(data.toString());		
      }
      
      //Send the response body 
      response.end();
   });   
  }).listen(8081);
  //Console will print the message
  console.log('Server running at http://127.0.0.1:8081/');

接下来,让我们在创建server.js的同一目录中创建以下名为index.htm的html文件。

<html>
   <head>
      <title>Sample Page</title>
   </head>
   
   <body>
      Hello World!   </body></html>

现在让我们运行server.js以查看输出-

$node server.js

验证输出。

Server running at http://127.0.0.1:8081/

向服务器发出请求

在任何浏览器中打开http://127.0.0.1:8081/index.htm,以查看以下输出。

https://img1.sycdn.imooc.com/611f1fd700017a2a06000342.jpg

在服务器端验证输出。

Server running at http://127.0.0.1:8081/Request for /index.htm received.

创建Web客户端

可以使用 http 模块创建Web客户端。让我们检查以下示例。

创建一个名为client.js的js文件-

var http=require('http');
//Options to be used by request 
var options={
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  
};
//Callback function is used to deal with 
responsevar callback=function(response) {
   //Continuously update stream with data
   var body='';
   response.on('data', function(data) {
      body += data;
   });
   
   response.on('end', function() {
      //Data received completely.
      console.log(body);
   });}
   //Make a request to the servervar
    req=http.request(options, callback);
    req.end();

现在从不同于server.js的其他命令终端运行client.js以查看输出-

$node client.js

验证输出。

<html>
   <head>
      <title>Sample Page</title>
   </head>
   
   <body>
      Hello World!   </body></html>

在服务器端验证输出。

Server running at http://127.0.0.1:8081/Request for /index.htm received.


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
PHP开发工程师
手记
粉丝
8
获赞与收藏
17

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消