之前有简单介绍nodejs的一篇文章(http://www.cnblogs.com/fangsmile/p/6226044.html)

HTTP服务器

Node内建有一个模块,利用它可以很容易创建基本的HTTP服务器。请看下面案例。

my_web_server.js

1 var http = require('http');
2 http.createServer(function (req, res) {
3   res.writeHead(200, {'Content-Type': 'text/plain'});
4   res.end('Hello World\n');
5 }).listen(8080);
6
7 console.log('Server running on port 8080.');

在上面,我说是的基本HTTP服务器。该例中所创建的并不是一个功能全面的HTTP服务器,它并不能处理任何HTML文件、图片。事实上,无论你请求什么,它都将返回“Hello World”。你运行该代码,并在浏览器中输入“http://localhost:8080”,你将看见该文本。

$ node my_web_server.js  

现在你可能已经注意到一些不一样的东西。你的Node.js应用并没有退出。这是因为你创建了一个服务器,你的Node.js应用将继续运行,并响应请求,直到你关闭它。

如果你希望它成为一个全功能的Web服务器,你必须检查所收到的请求,读取合适的文件,并返回所请求的内容。

首先实现一个处理静态资源的函数,其实就是对本地文件的读取操作,这个方法已满足了上面说的静态资源的处理。

 1 var http = require('http');
 2 var fs = require("fs");
 3 http.createServer(function (req, res) {
 4     staticResHandler("G:/nodemodule/home_index.html", "html", res)
 5 }).listen(8080);
 6 function staticResHandler(localPath, ext, response) {
 7     fs.readFile(localPath, "binary", function (error, file) {
 8         if (error) {
 9             response.writeHead(500, { "Content-Type": "text/plain" });
10             response.end("Server Error:" + error);
11         } else {
12             response.writeHead(200, { "Content-Type": 'text/html' });
13             response.end(file, "binary");
14         }
15     });
16 }
17 console.log('Server running on port 8080.');

进一步使用nodejs创建web服务器处理get、post请求

path.js :

  1  var http = require('http');
  2  var fs = require('fs');
  3  var assert = require('assert');
  4  var path = require('path');
  5  var url = require('url');
  6
  7  var config = {
  8     port:81
  9  }
 10  var sum = 0;
 11  var response = {
 12     "content":[
 13         {
 14             "type":"11111",
 15             "name":"hello world"
 16         },
 17         {
 18             "type":"22222",
 19             "name":"world Map"
 20         }
 21
 22     ]
 23 }
 24
 25  http.createServer(function(req,res){
 26     sum ++;
 27     var pathName = url.parse(req.url).pathname;
 28     var localPath = "";
 29     var ext = path.extname(pathName);
 30     var Type = req.method;
 31     if(Type =='POST'){
 32         var resData = {};
 33         var body = '';
 34         req.on('data',function(data){
 35             body += data;
 36             console.log('data' + data);
 37         });
 38         req.on('end',function(data){
 39             var len = body.split('&').length;
 40             if(len > 0){
 41                 for(var i=0;i<len;i++){
 42                     var key = body.split('&')[i];
 43                     resData[key.split('=')[0]] = key.split('=')[1];
 44                 }
 45             }
 46             res.writeHead(200,{'Content-Type':'application/x-json'});
 47             res.end(JSON.stringify(resData),'binary');
 48         });
 49
 50     }
 51     else if(Type =='GET'){
 52         if(pathName =='/'){
 53             pathName = '/html/index.html';
 54         }
 55         if(ext.length > 0){
 56             localPath = '.' + pathName;
 57         }
 58         else{
 59             localPath ='./src' + pathName;
 60         }
 61         console.log('localPath:' + localPath);
 62         fs.exists(localPath,function(exists){
 63             if(exists){
 64                 console.log(localPath + ' is exists');
 65                 fs.readFile(localPath,'binary',function(err,file){
 66                     if(err){
 67                         res.writeHead(500,{'Content-Type':'text/plain'});
 68                         res.end('server Error:' + err);
 69                     }
 70                     else{
 71                         res.writeHead(200,{'Content-Type':getContentTypeByExt(ext)});
 72                         if(ext === '.json'){
 73                             res.end(JSON.stringify(response),'binary');
 74                         }
 75                         else{
 76                             res.end(file,'binary');
 77                         }
 78
 79                     }
 80                 })
 81             }
 82             else{
 83                 res.writeHead(400,{'Content-Type':'text/plain'});
 84                 res.end('404:File Not found');
 85             }
 86
 87
 88     })
 89     }
 90
 91
 92  }).listen(config.port);
 93
 94 function getContentTypeByExt(ext) {
 95     ext = ext.toLowerCase();
 96     if (ext === '.htm' || ext === '.html')
 97         return 'text/html';
 98     else if (ext === '.js')
 99         return 'application/x-javascript';
100     else if (ext === '.css')
101         return 'text/css';
102     else if (ext === '.jpe' || ext === '.jpeg' || ext === '.jpg')
103         return 'image/jpeg';
104     else if (ext === '.png')
105         return 'image/png';
106     else if (ext === '.ico')
107         return 'image/x-icon';
108     else if (ext === '.zip')
109         return 'application/zip';
110     else if (ext === '.doc')
111         return 'application/msword';
112     else if (ext === '.json')
113         return 'application/x-json';
114     else
115         return 'text/plain';
116 }
117
118  console.log('new server is running: http://127.0.0.1:81')

View Code

index.html

<html>
<head>
<title>Sample Page</title><meta charset="UTF-8">
</head>
<link rel="stylesheet" href="../css/index.css"/>
<body>
Hello World!
<div class="music_class"><img src="../img/music_class.png" alt="分类图片"/>
</div>
<div><div>get请求获取的数据:</div><ul class="music_category_list"></ul>
</div>
<div><button class='postClick'>点击POST请求</button><div class='postDiv'><span>post请求获取的数据:</span><span class='postData'></span></div>
</div>
</body>
<script src="../js/lib/jquery-1.11.3.min.js"></script>
<script src="../js/page/index.js"></script>
</html>

index.js

 1 $(document).ready(function(){
 2     function createEle(){
 3         var img = new Image();
 4         img.src = "../img/music_hot.png";
 5         img.onload = function(){
 6             var imgDom = '<img src="../img/music_hot.png"/>';
 7             $('.music_class').append(imgDom);
 8         }
 9     }
10     createEle();
11     (function getDate(){
12         var XHR = $.ajax({
13                 timeout : 20000,
14                 dataType : 'json',
15                 type : 'GET',
16                 url : '../package.json',
17                 data : '',
18                 beforeSend : function (request) {
19                     request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
20                 },
21                 complete : function(XMLHttpRequest, status) {
22                     if (status == 'timeout') {
23                         //theUIApp.tip($("body"), "网络异常,请检查网络");
24                         util.toast("网络异常,请检查网络");
25                     }
26                 },
27                 success : function (result) {
28                     var LiLength = result.content.length;
29                     if(LiLength > 0){
30                         for(var i=0;i<LiLength;i++){
31                             var inp = '<li>' + result.content[i].name + '</li>';
32                             $('.music_category_list').append(inp);
33                         }
34                     }
35                 },
36                 error : function (result) {
37                     console.log(result)
38                 }
39             });
40     })();
41
42     $('.postClick').click(function(){
43         Post();
44     })
45
46     function Post(){
47         var option = {
48             name:'zhangsan',
49             age:'15'
50         }
51         var XHR = $.ajax({
52             timeout : 20000,
53             dataType : 'json',
54             type : 'POST',
55             url : '../package.json',
56             data : option,
57             beforeSend : function (request) {
58                 request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
59             },
60             complete : function(XMLHttpRequest, status) {
61                 if (status == 'timeout') {
62                     //theUIApp.tip($("body"), "网络异常,请检查网络");
63                     util.toast("网络异常,请检查网络");
64                 }
65             },
66             success : function (result) {
67                 if(result){
68                     $('.postData').text(result.name);
69                 }
70             },
71             error : function (result) {
72                 console.log(result)
73             }
74         });
75     }
76 })

View Code

index.css

 1 @charset "utf-8";
 2 html{ height: 100%}
 3 body{
 4     font-family:"Microsoft YaHei",Arial,Helvetica,sans-serif,"宋体";
 5     font-size:3.5rem;
 6 }
 7 li{
 8     list-style-type:none;
 9 }
10 .music_class{
11     width:100%;
12     margin:10px;
13 }
14 .music_class img{
15     width:95%;
16 }
17 .music_category_list{
18     margin:10px;
19 }
20 .music_category_list li{
21     width:95%;
22     margin:5px;
23     padding:5px;
24     border:2px solid #ccc;
25 }
26 .postData{
27     width:100%;
28     color:blue;
29     fonst-size:20px;
30     text-align:center;
31 }
32 button{
33     font-size:30px;
34     width:300px;
35     height:100px;
36 }

View Code

建议服务器的相关代码下载地址:http://files.cnblogs.com/files/fangsmile/nodejs-http%E6%9C%8D%E5%8A%A1%E5%99%A8.zip

下载下来运行:node path    然后访问 http://127.0.0.1:81/index.html

转载于:https://www.cnblogs.com/fangsmile/p/6226963.html

nodejs创建http服务器相关推荐

  1. 应用Nodejs创建web服务器

    //创建web服务器,设置端口,根据浏览器的URL做出响应 /index    响应'<h2>这是首页</h2>'              /list         响应文 ...

  2. Nodejs创建https服务器(Windows 7)

    为了实验一下WebRTC,搭了个简单的https服务器.说说步骤: 生成OpenSSL证书 使用Nodejs的https模块建立服务器 OpenSSL 证书 我机子Windows 7,安装了Cygwi ...

  3. nodejs创建rtmp-streamer服务器

    https://blog.csdn.net/qq_38652871/article/details/89632256 https://blog.csdn.net/weixin_44692055/art ...

  4. nodejs 创建一个静态资源服务器 +路由

    0.补充 1.Node.js 创建的第一个应用 1.引入 http 模块 var http = require("http"); 2.创建服务器 接下来我们使用 http.crea ...

  5. nodejs 本地php服务器,node.js创建本地服务器详解

    本文主要和大家分享node.js创建本地服务器详解,简易上手node.js后,我们就可以在自己电脑上创建本地服务器了.希望能帮助到大家. 一.先上代码.//请求Node.js自带的http模块. va ...

  6. 使用Nodejs创建一个Web服务器应如何操作?以及路由相关知识了解

    文章目录 Nodejs创建一个Web服务器 Node.js创建第一个应用 Web服务器介绍 Nodejs创建一个Web服务器 路由 EJS模块引擎 Get.Post 获取GET传值 获取POST传值 ...

  7. Nodejs 使用express模块创建一个服务器

    使用express模块创建一个服务器 新建一个文件夹,文件夹名字非中文,名字也不要和模块名字一样 npm init -y 初始化 下载模块,去npm官网搜索模块,用他的说明来下 如果下载失败,则用 n ...

  8. node aws 内存溢出_如何使用Node.js和AWS快速创建无服务器RESTful API

    node aws 内存溢出 by Mark Hopson 马克·霍普森(Mark Hopson) 如何使用Node.js和AWS快速创建无服务器RESTful API (How to quickly ...

  9. 使用noode.js创建一个服务器

    一.简单的静态服务器 1.代码解析 var http = require('http') // http是nodejs里面的一个模块,这个对象能够提供实现底层的方法.我们通过require去加载这个模 ...

最新文章

  1. python之文件读写和异常处理
  2. connection refused_ERR_CONNECTION_REFUSED
  3. 解决MySQL忘记root密码
  4. java nio集群_java – Hazelcast:连接到远程集群
  5. 【BZOJ4816】数字表格,反演+枚举约数
  6. 跨语言之间的socket通信(C--Java的握手)(基础篇转)
  7. 计算机算法设计与分析教学大纲,《算法设计与分析》教学大纲
  8. ng-show和ng-if的区别和使用场景
  9. [笔记] 线段树的兄弟姐妹们
  10. 汇川plc c语言,汇川plc可编程控制器模块种类
  11. PIC单片机的入门认识(以PIC12为学习目标)
  12. 解决vscode打开txt文件乱码
  13. RAW格式转存PNG图片
  14. igs时间和utc_世界协调时间(UTC)与中国标准时间
  15. C++构造函数的default和delete
  16. HDFS配置之NN-SNN-DN
  17. 日本药妆店扫货必备手册·收藏版
  18. ORACLE中dual的详解及其故障恢复
  19. Div CSS网页布局对网站搜索引擎优化的影响
  20. 面试中更多会考核相关技能的项目经验——再论程序员该如何准备面试

热门文章

  1. UIApplication深入研究
  2. while正逆序的测试结果
  3. POJ PKU 2305 java大数进制转化 JAVA 大数转换成字符串 转
  4. 用Lambda表达式进行函数式编程
  5. 算法(一):二分查找法
  6. zookeeper学习笔记001-Address already in use: bind启动报错
  7. 微信小程序开发学习笔记008--微信小程序项目02
  8. EJB3.0学习笔记---Stateless Session Bean的原理:
  9. opencv实现多个图拼接成一个图
  10. 最近ubuntu+gpu装机记录