运行一个简单的node.js 服务应用

利用node.js - web 模块

Web服务器是用于处理使用HTTP协议请求并返回网页作为响应到客户端的软件应用程序。 Web服务器通常提供HTML文档并伴随着图片,样式表和脚本。大多数Web服务器还支持使用脚本语言作为服务器端脚本,或重定向到从数据库中获取数据的执行特定任务的应用程序服务器,执行复杂的逻辑等,Web服务器然后返回应用服务器到客户端输出。

Apache web服务器是最常见的一个网络服务器。它是一个开源项目。

路径定位过程

web服务器映射通过URL,统一资源定位符对资源文件的路径。可以是一个本地文件系统或一个外部/内部程序。

客户端使用的浏览器发起一个URL请求:http://www.test-example-site.com/website/index.htm.

浏览器发起的一个请求是:

GET /website/index.htm HTTP /1.1
HOST www.test-example-site.com

Web服务器将追加路径到根目录。举个例子:根目录是home/www,那么实际路径将被转换为 home/www/website/index.htm.

web网络架构

web应用程序使用分为四层。 

  • Client - 此层是由Web浏览器,移动浏览器或应用程序,它可以发起HTTP请求到服务器。

  • Server - 这一层包括可拦截发出的客户端请求,并将其传递到由Web服务器响应。

  • Business - 这一层由应用程序服务器组成,它通过利用Web服务器执行动态任务。这一层交互通过数据库或某些外部程序数据层。

  • Data - 此层由数据库或任何来源的数据。

 一个简单例子演示;

server.js

 1 var http = require('http');
 2 var fs = require('fs');
 3 var url = require('url');
 4 
 5 http.createServer(function(request,response){
 6     var pathname = url.parse(request.url).pathname;
 7     console.log('request for' + pathname + 'received.');
 8     fs.readFile(pathname.substr(1),function(err,data){
 9         if(err){
10             console.log(err.stack);
11             response.writeHead(404,{'Content-Type': 'text/html'});
12         }else{
13             response.writeHead(200,{'Content-Type': 'text/html'})
14             response.write(data.toString());
15         }
16         response.end();
17     })
18 }).listen(8081);
19 console.log('server runing at http://127.0.0.1:8081/')

当前目录执行node server.js 查看结果

浏览器可响应请求并打开 http://127.0.0.1:8081/+文件名,可打开当前文件下的html页面。

client.js

//http module is required to create a web client
var http = require('http');

//options are to be used by request 
var options = {
   host: 'localhost',
   port: '8081',
   path: '/test.html'  
};


//callback function is used to deal with response
var 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 server
var req = http.request(options, callback);
req.end();

当前目录执行node client.js ;

可将 http://127.0.0.1:8081/ 端口自动响应 /test.html 文件;

 node.js - Express应用程序

Express JS是用于创建Node JS的Web应用程序非常流行的Web应用程序框架。它提供了一个集成的环境便于快速开发基于Node的Web应用程序。Express框架是基于连接的中间件引擎并使用Jade HTML模板框架来做HTML模板。以下是一些Express 框架的核心功能:

  • 允许设立中间件来响应HTTP请求

  • 定义了用于执行基于HTTP方法和URL不同作用的路由表

  • 允许动态渲染基于参数传递给模板的HTML页面

安装 

当前目录下cmd 中执行 npm install express -g 安装express应用(-g表示全局)

express生成器 npm install express-generator -g (-g表示全局);

demo

cmd 下执行express firstApplication

再执行npm install 安装firstApplication的依赖关系

当前文件加下生成 firstApplication 文件夹, firstApplication中包含

  • package.json 是应用程序描述符文件包含在依赖项列表中,应用程序使用 Node 的其他属性

  • app.js 包含了服务器的初始化代码

  • bin是用于存储在生产模式下的应用程序

  • public用于存储图像,样式表和JavaScript文件

  • routes 包含路由处理程序

  • views 包含HTML模板来生成Web应用各种视图

 更新app.js

 1 var createError = require('http-errors');
 2 var express = require('express');
 3 var path = require('path');
 4 var cookieParser = require('cookie-parser');
 5 var logger = require('morgan');
 6 var http = require('http');// set
 7 var bodyParser = require('body-parser'); // set
 8 
 9 var indexRouter = require('./routes/index');
10 var usersRouter = require('./routes/users');
11 
12 var app = express();
13 
14 // view engine setup
15 app.set('port', process.env.PORT || 8891); //set
16 app.set('views', path.join(__dirname, 'views'));
17 app.set('view engine', 'jade');
18 
19 app.use(logger('dev'));
20 app.use(express.json());
21 app.use(express.urlencoded({ extended: false }));
22 app.use(cookieParser());
23 app.use(express.static(path.join(__dirname, 'public')));
24 
25 // 前台主页面
26 app.use('/', indexRouter);
27 // 后台主页面
28 app.use('/users', usersRouter);
29 
30 // catch 404 and forward to error handler
31 app.use(function(req, res, next) {
32   next(createError(404));
33 });
34 
35 // error handler
36 app.use(function(err, req, res, next) {
37   // set locals, only providing error in development
38   res.locals.message = err.message;
39   res.locals.error = req.app.get('env') === 'development' ? err : {};
40 
41   // render the error page
42   res.status(err.status || 500);
43   res.render('error');
44 });
45 
46 http.createServer(app).listen(app.get('port'),function(){
47   console.log('Express server listening on port' + app.get('port'));
48 })
49 
50 module.exports = app;
app.js

运行app.js文件:node app.js

浏览器可通过http://127.0.0.1:8081/和http://127.0.0.1:8081/users访问到前后台主页面;

这是由app.js 中的基本的路由绑定的

由routes文件夹中对应的index.js和users.js创建出index.html和users.html;

当Node服务器接收到一个主页的请求,express路由器渲染索引页是使用模板index.jade同时传递参数title的值为'Express'。

原文地址:https://www.cnblogs.com/bacydm/p/9795482.html