nodejs创建http服务器
之前有简单介绍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服务器,你必须检查所收到的请求,读取合适的文件,并返回所请求的内容。
首先实现一个处理静态资源的函数,其实就是对本地文件的读取操作,这个方法已满足了上面说的静态资源的处理。
var http = require('http');
var fs = require("fs");
http.createServer(function (req, res) {
staticResHandler("G:/nodemodule/home_index.html", "html", res)
}).listen(8080);
function staticResHandler(localPath, ext, response) {
fs.readFile(localPath, "binary", function (error, file) {
if (error) {
response.writeHead(500, { "Content-Type": "text/plain" });
response.end("Server Error:" + error);
} else {
response.writeHead(200, { "Content-Type": 'text/html' });
response.end(file, "binary");
}
});
}
console.log('Server running on port 8080.');
进一步使用nodejs创建web服务器处理get、post请求
path.js :
var http = require('http');
var fs = require('fs');
var assert = require('assert');
var path = require('path');
var url = require('url');
var config = {
port:81
}
var sum = 0;
var response = {
"content":[
{
"type":"11111",
"name":"hello world"
},
{
"type":"22222",
"name":"world Map"
}
]
}
http.createServer(function(req,res){
sum ++;
var pathName = url.parse(req.url).pathname;
var localPath = "";
var ext = path.extname(pathName);
var Type = req.method;
if(Type =='POST'){
var resData = {};
var body = '';
req.on('data',function(data){
body += data;
console.log('data' + data);
});
req.on('end',function(data){
var len = body.split('&').length;
if(len > 0){
for(var i=0;i<len;i++){
var key = body.split('&')[i];
resData[key.split('=')[0]] = key.split('=')[1];
}
}
res.writeHead(200,{'Content-Type':'application/x-json'});
res.end(JSON.stringify(resData),'binary');
});
}
else if(Type =='GET'){
if(pathName =='/'){
pathName = '/html/index.html';
}
if(ext.length > 0){
localPath = '.' + pathName;
}
else{
localPath ='./src' + pathName;
}
console.log('localPath:' + localPath);
fs.exists(localPath,function(exists){
if(exists){
console.log(localPath + ' is exists');
fs.readFile(localPath,'binary',function(err,file){
if(err){
res.writeHead(500,{'Content-Type':'text/plain'});
res.end('server Error:' + err);
}
else{
res.writeHead(200,{'Content-Type':getContentTypeByExt(ext)});
if(ext === '.json'){
res.end(JSON.stringify(response),'binary');
}
else{
res.end(file,'binary');
}
}
})
}
else{
res.writeHead(400,{'Content-Type':'text/plain'});
res.end('404:File Not found');
}
})
}
}).listen(config.port);
function getContentTypeByExt(ext) {
ext = ext.toLowerCase();
if (ext === '.htm' || ext === '.html')
return 'text/html';
else if (ext === '.js')
return 'application/x-javascript';
else if (ext === '.css')
return 'text/css';
else if (ext === '.jpe' || ext === '.jpeg' || ext === '.jpg')
return 'image/jpeg';
else if (ext === '.png')
return 'image/png';
else if (ext === '.ico')
return 'image/x-icon';
else if (ext === '.zip')
return 'application/zip';
else if (ext === '.doc')
return 'application/msword';
else if (ext === '.json')
return 'application/x-json';
else
return 'text/plain';
}
console.log('new server is running: http://127.0.0.1:81')
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
$(document).ready(function(){
function createEle(){
var img = new Image();
img.src = "../img/music_hot.png";
img.onload = function(){
var imgDom = '<img src="../img/music_hot.png"/>';
$('.music_class').append(imgDom);
}
}
createEle();
(function getDate(){
var XHR = $.ajax({
timeout : 20000,
dataType : 'json',
type : 'GET',
url : '../package.json',
data : '',
beforeSend : function (request) {
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
},
complete : function(XMLHttpRequest, status) {
if (status == 'timeout') {
//theUIApp.tip($("body"), "网络异常,请检查网络");
util.toast("网络异常,请检查网络");
}
},
success : function (result) {
var LiLength = result.content.length;
if(LiLength > 0){
for(var i=0;i<LiLength;i++){
var inp = '<li>' + result.content[i].name + '</li>';
$('.music_category_list').append(inp);
}
}
},
error : function (result) {
console.log(result)
}
});
})();
$('.postClick').click(function(){
Post();
})
function Post(){
var option = {
name:'zhangsan',
age:'15'
}
var XHR = $.ajax({
timeout : 20000,
dataType : 'json',
type : 'POST',
url : '../package.json',
data : option,
beforeSend : function (request) {
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
},
complete : function(XMLHttpRequest, status) {
if (status == 'timeout') {
//theUIApp.tip($("body"), "网络异常,请检查网络");
util.toast("网络异常,请检查网络");
}
},
success : function (result) {
if(result){
$('.postData').text(result.name);
}
},
error : function (result) {
console.log(result)
}
});
}
})
index.css
@charset "utf-8";
html{ height: 100%}
body{
font-family:"Microsoft YaHei",Arial,Helvetica,sans-serif,"宋体";
font-size:3.5rem;
}
li{
list-style-type:none;
}
.music_class{
width:100%;
margin:10px;
}
.music_class img{
width:95%;
}
.music_category_list{
margin:10px;
}
.music_category_list li{
width:95%;
margin:5px;
padding:5px;
border:2px solid #ccc;
}
.postData{
width:100%;
color:blue;
fonst-size:20px;
text-align:center;
}
button{
font-size:30px;
width:300px;
height:100px;
}
建议服务器的相关代码下载地址: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
nodejs创建http服务器的更多相关文章
- Nodejs创建HTTPS服务器
Nodejs创建HTTPS服务器 从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发.Nodejs框架是基于V8的引擎,是目前速度最快的Jav ...
- NodeJs 创建 Web 服务器
以下是演示一个最基本的 HTTP 服务器架构(使用8081端口),创建 ser.js 文件,代码如下所示: var http = require('http'); var fs = require(' ...
- Nodejs创建https服务器(Windows 7)
为了实验一下WebRTC,搭了个简单的https服务器.说说步骤: 生成OpenSSL证书 使用Nodejs的https模块建立服务器 OpenSSL 证书 我机子Windows 7,安装了Cygwi ...
- Express与NodeJs创建服务器的两种方法
NodeJs创建Web服务器 var http = require('http'); var server = http.createServer(function(req, res) { res.w ...
- Nodejs+Express创建HTTPS服务器
为了使我的Nodejs服务器提供HTTPS服务,学习了一下如何利用express创建https服务器,现记录如下.(一点一点的积累与掌握吧) 1. Http与Https 介绍 HTTP: 超文本传输协 ...
- 使用nodejs的net模块创建TCP服务器
使用nodejs的net模块创建TCP服务器 laiqun@msn.cn Contents 1. 代码实现 2. 使用telnet连接服务器测试 3. 创建一个TCP的client 1. 代码实现 ; ...
- 使用nodejs的http模块创建web服务器
使用nodejs的http模块创建web服务器 laiqun@msn.cn Contents 1. web服务器基础知识 2. Node.js的Web 服务器 3. 代码实现 1. web服务器基础知 ...
- nodejs学习笔记<二> 使用node创建基础服务器
创建服务器的 server.js 内容. var http = require("http"); // 引用http模块 http.createServer(function(re ...
- nodejs的express框架创建https服务器
一 openssl创建https私钥和证书 1.下载windows版openssl: http://slproweb.com/products/Win32OpenSSL.html Win64OpenS ...
随机推荐
- 在 ML2 中配置 OVS flat network - 每天5分钟玩转 OpenStack(133)
前面讨论了 OVS local network,今天开始学习 flat network. flat network 是不带 tag 的网络,宿主机的物理网卡通过网桥与 flat network 连接, ...
- 高性能IO模型浅析
高性能IO模型浅析 服务器端编程经常需要构造高性能的IO模型,常见的IO模型有四种: (1)同步阻塞IO(Blocking IO):即传统的IO模型. (2)同步非阻塞IO(Non-blocking ...
- ASP.NET内置对象的总结
1. Response对象可形象的称之为响应对象,用于将数据从服务器发送回浏览器. 实例源码:链接: http://pan.baidu.com/s/1dDCKQ8x 密码: ihq0 2. Requ ...
- pt-online-schema-change中update触发器的bug
pt-online-schema-change在对表进行表结构变更时,会创建三个触发器. 如下文测试案例中的t2表,表结构如下: mysql> show create table t2\G . ...
- Solr 排除查询
前言 solr排除查询也就是我们在数据库和程序中经常处理的不等于,solr的语法是在定语前加[-].. StringBuilder sbHtml=new StringBuilder(); shBhtm ...
- MongoDB系列(二):C#应用
前言 上一篇文章<MongoDB系列(一):简介及安装>已经介绍了MongoDB以及其在window环境下的安装,这篇文章主要讲讲如何用C#来与MongoDB进行通讯.再次强调一下,我使用 ...
- [数据结构]——堆(Heap)、堆排序和TopK
堆(heap),是一种特殊的数据结构.之所以特殊,因为堆的形象化是一个棵完全二叉树,并且满足任意节点始终不大于(或者不小于)左右子节点(有别于二叉搜索树Binary Search Tree).其中,前 ...
- 微信小程序开发日记——高仿知乎日报(上)
本人对知乎日报是情有独钟,看我的博客和github就知道了,写了几个不同技术类型的知乎日报APP 要做微信小程序首先要对html,css,js有一定的基础,还有对微信小程序的API也要非常熟悉 我将该 ...
- webix前端架构的项目应用
webix框架兼容javascript.HTML.CSS,应用比较灵活,应用框架时,配合后台webAPI,整个web项目里面,App文件夹保存前台的多语言文件,图片文件,webix原代码js.css, ...
- Android Studio 编译单个module
前期自己要把gradle环境变量配置好 在Terminal中gradle命令行编译apk 输入gradle assembleRelease 会编译全部module编译单个modulecd ./xiru ...