构建web应用示例
1.1 请求方法的判断
var http = require('http');
var server = http.createServer(function(request,response){
switch(request.method){
case 'POST':
update(request,response);
break;
case 'DELETE':
remove(request,response);
break;
case 'PUT':
create(request,response);
break;
case 'GET':
default:
get(request,response);
}
});
server.listen(8000,'127.0.0.1');
1.2 路径解析
var http = require('http');
var url = require('url');
var server = http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname;
var paths = pathname.split('/');
var controler = paths[1] || 'index';
var action = paths[2] || 'action';
var args = paths.slice(3);
if(handles[controler]&&handles[controler][action]){
handles[controler][action].apply(null,[request,response].concat(args));
}else{
response.writeHead(500);
response.end('error');
}
});
server.listen(8000,'127.0.0.1');
var handles = {};
handles.index = {};
handles.index.index = function(request,response){
response.writeHead(200);
response.end('success');
}
1.3 查询字符串
var http = require('http');
var url = require('url');
var server = http.createServer(function(request,response){
request.query = url.parse(request.url,true).query;
handle(request,response);
});
server.listen(8000,'127.0.0.1');
var handle = function(request,response){
}
1.4 Cookie
var parseCookie = function(cookie){
var cookies = {};
if(!cookie){
return cookies;
}
var list = cookie.split(';');
for(var i=0;i<list.length;i++){
var pair = list[i].split('=');
cookies[pair[0].trim()] = pair[1];
}
return cookies;
}
var serializeCookie = function(name,value,options){
var pairs = [name+'='+encodeURI(value)];
options = options || {};
if(options.maxAge){
pairs.push('Max-Age='+options.maxAge);
}
if(options.domain){
pairs.push('Domain='+options.domain);
}
if(options.path){
pairs.push('Path='+options.path);
}
if(options.expires){
pairs.push('Expires='+options.expires.toUTCString());
}
if(options.httpOnly){
pairs.push('HttpOnly');
}
if(options.secure){
pairs.push('Secure');
}
return pairs.join('; ');
}
var http = require('http');
var url = require('url');
var server = http.createServer(function(request,response){
request.cookies = parseCookie(request.headers.cookie);
handle(request,response);
});
server.listen(8000,'127.0.0.1');
var handle = function(request,response){
console.log(request.cookies);
}
1.5 Session
var sessions = {};
var key = 'session_id';
var EXPIRES = 20*60*1000;
var generate = function(){
var session = {};
session.id = (new Date()).getTime()+Math.random();
session.cookie = {
expire:(new Date()).getTime()+EXPIRES
}
sessions[session.id] = session;
return session;
}
var http = require('http');
var url = require('url');
Function.prototype.before = function(beforefn){
var _self = this;
return function(){
beforefn.apply(this,arguments);
return _self.apply(this,arguments);
}
}
var server = http.createServer(function(request,response){
request.cookies = parseCookie(request.headers.cookie);
var id = request.cookies[key];
if(!id){
request.session = generate();
}else{
var session = sessions[id];
if(session){
if(session.cookie.expire > (new Date()).getTime()){
session.cookie.expire = (new Date()).getTime()+EXPIRES;
request.session = session;
}else{
delete sessions[id];
request.session = generate();
}
}else{
request.session = generate();
}
}
response.writeHead.before(function(){
var cookies = response.getHeader('Set-Cookie');
var session = serializeCookie(key,request.session.id);
cookies = Array.isArray(cookies)?cookies.concat(session):[cookies,session];
response.setHeader('Set-Cookie',cookies);
});
handle(request,response);
});
server.listen(8000,'127.0.0.1');
var handle = function(request,response){
console.log(request.cookies);
response.writeHead(200);
response.end('ok');
}
1.6 数据上传
var http = require('http');
var url = require('url');
var querystring = require('querystring');
var xml2js= require('xml2js');
var formidable= require('formidable');
var hasBody = function(request){
return 'transfer-encoding' in request.headers || 'content-length' in request.headers;
}
var mime = function(request){
var str = request.headers['content-type'] || '';
return str;
}
var server = http.createServer(function(request,response){
if(hasBody(request)){
var buffers = [];
request.on('data',function(chunk){
buffers.push(chunk);
});
request.on('end',function(){
request.rawBody = Buffer.concat(buffers).toString();
handle(request,response);
});
}
else{
handle(request,response);
}
});
server.listen(8000,'127.0.0.1');
var handle = function(request,response){
//表单
if(mime(request) == 'application/x-www-form-urlencoded'){
request.body = querystring.parse(request.rawBody);
handle(request,response);
}else if(mime(request) == 'application/json'){
request.body = JSON.parse(request.rawBody);
handle(request,response);
}else if(mime(request) == 'application/xml'){
xml2js.parseString(request.rawBody,function(err,xml){
request.body = xml;
handle(request,response);
});
}else if(mime(request) == 'multipart/form-data'){
var form = new formidable.IncomingForm();
form.parse(request,function(err,fields,files){
request.body = fields;
request.files = files;
handle(request,response);
});
}else{
console.log('ok');
}
}
1.7 路由解析
var pathRegexp = function(path){
var keys = [];
path = path.concat(strict ?'':'/?')
.replace('/\/\(\g','(?:/')
.replace('/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g',function(_,slash,format,key,capture,optional,star){
keys.push(key);
slash = slash || '';
return ''
+(optional?'':slash)
+'(?:'
+(optional?slash:'')
+(format||'')+(capture || (format && '([^/.]+?)' || '([^/+?])')) +')'
+(optional || '')
+(star?'(/*)?':'');
})
.replace('/([\/.])/g','\\$1')
.replace('/\*/g','(.*)');
return {
keys:keys,
regexp: new RegExp('^'+path+'$')
};
}
var routes = {'all':[]};
var app={};
app.use = function(path){
var handle;
if(typeof path === 'string'){
handle = {
path:pathRegexp(path),
stack:Array.prototype.slice.call(arguments,1)
}
}else{
handle = {
path:pathRegexp('/'),
stack:Array.prototype.slice.call(arguments,0)
}
}
routes.all.push(handle);
}
['get','put','delete','post'].forEach(function(method){
routes[method] = [];
app[method] = function(path){
var handle = {
path:pathRegexp(path),
stack:Array.prototype.slice.call(arguments,1)
}
routes[method].push(handle);
}
});
var querystring = function(request,response,next){
try {
request.query = url.parse(request.url,true).query;
next();
} catch (err) {
next(err);
}
}
var cookie = function(request,response,next){
var cookie = request.headers.cookie;
var cookies = {};
if(cookie){
var list = cookie.split(';');
for(var i=0;i<list.length;i++){
var pair = list[i].split('=');
cookies[pair[0].trim()] = pair[1];
}
}
request.cookies = cookies;
next();
}
var match = function(pathname,routes){
var stacks = [];
for(var i=0;i<routes.length;i++){
var route = routes[i];
var reg = route.path.regexp;
var matched = reg.exec(pathname);
if(matched){
stacks = stacks.concat(route.stack);
}
}
return stacks;
}
var handle404 = function(request,response){
console.log(404)
}
var handle500 = function(err,request,response,stacks){
console.log(500)
}
var handle = function(request,response,stacks){
var next = function(err){
if(err){
return handle500(err,request,response,stacks)
}
var middleware = stacks.shift();
if(middleware){
try {
middleware(request,response,next);
} catch (err) {
next(err);
}
}
}
next();
}
var server = http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname;
var method = request.method.toLowerCase();
var stacks = match(pathname,routes.all);
if(routes.hasOwnPerperty(method)){
stacks.concat(match(pathname,routes[method]));
}
if(stacks.length){
handle(request,response,stacks);
}else{
handle404(request,response)
}
});
server.listen(8000,'127.0.0.1');
构建web应用示例的更多相关文章
- Node.js高级编程读书笔记 - 4 构建Web应用程序
Outline 5 构建Web应用程序 5.1 构建和使用HTTP中间件 5.2 用Express.js创建Web应用程序 5.3 使用Socket.IO创建通用的实时Web应用程序 5 构建Web应 ...
- 高效构建Web应用 教你玩转Play框架 http://www.anool.net/?p=577
Play 框架是一个完整的Web应用开发框架,覆盖了Web应用开发的各个方面.Play 框架在设计的时候借鉴了流行的 Ruby on Rails 和 Grails 等框架,又有自己独有的优势.使用 P ...
- threejs构建web三维视图入门教程
本文是一篇简单的webGL+threejs构建web三维视图的入门教程,你可以了解到利用threejs创建简单的三维图形,并且控制图形运动.若有不足,欢迎指出. 本文使用的框架是three.js gi ...
- 实战案例--Grunt构建Web程序
GruntJS构建Web程序.使用Gruntjs来搭建一个前端项目,然后使用grunt合并,压缩JS文件,熟练了node.js安装和grunt.js安装后,接下来来实战一个案例,案例是根据snandy ...
- 使用Vert.x构建Web服务器和消息系统
如果你对Node.js感兴趣,Vert.x可能是你的下一个大事件:一个建立在JVM上一个类似的架构企业制度. 这一部分介绍Vert.x是通过两个动手的例子(基于Vert.x 2.0). 当Node.j ...
- 用 Python 构建 web 应用
用 Python 构建 web 应用 如果说仅仅要用 Python 构建 web 应用,可以将 socket 连接.HTTP 原始请求和响应格式等涉及网络基础的东西交给现成的库来实现,只需要专注于 w ...
- NodeJs+http+fs+request+cheerio 采集,保存数据,并在网页上展示(构建web服务器)
目的: 数据采集 写入本地文件备份 构建web服务器 将文件读取到网页中进行展示 目录结构: package.json文件中的内容与上一篇一样:NodeJs+Request+Cheerio 采集数据 ...
- 使用EXtjs6.2构建web项目
一.项目简介 众所周知ext是一款非常强大的表格控件,尤其是里边的grid为用户提供了非常多的功能,现在主流的还是用extjs4.0-4.2,但是更高一点的版本更加符合人的审美要求.因此,在今天咱们构 ...
- 《深入浅出Node.js》第8章 构建Web应用
@by Ruth92(转载请注明出处) 第8章 构建Web应用 一.基础功能 请求方法:GET.POST.HEAD.DELETE.PUT.CONNECT GET /path?foo=bar HTTP/ ...
随机推荐
- acdream1233 Royal Federation (构造?)
http://acdream.info/problem?pid=1233 Andrew Stankevich's Contest (3) ASC 3 Royal Federation Special ...
- IOS表情存入MYSQL数据库失败
从 MySQL 5.5.3 开始,MySQL 支持一种 utf8mb4 的字符集,这个字符集能够支持 4 字节的 UTF8 编码的字符. utf8mb4 字符集能够完美地向下兼容 utf8 字符串.在 ...
- min-device-pixel-ratio
Devices with -webkit-min-device-pixel-ratio: 2.0 All Macs with Retina displaysApple iPhone 4Apple iP ...
- HTTP报文详解
二.HTTP请求首部字段 1 Accept 2 Accept-Charset 3 Accept-Encoding 4 Accept-Language 5 Authorization 6
- 解析posix与perl标准的正则表达式区别 ---PHP
正则表达式(Regular Expression,缩写为regexp,regex或regxp),又称正规表达式.正规表示式或常规表达式或正规化表示法或正规表示法,是指一个用 来描述或者匹配一系 ...
- [译]git reset
git reset 如果说git revert是一个安全的撤销方式, 那么git reset就是一个非常危险的方法了. 当你使用git reset撤销的时候, 你没有可能在回到最初了-他是一个永久的不 ...
- PHP基础之 重载 的实现方式
===================PHP中的伪重载Overloading================== PHP中没有像C#或java中的重载,但可以通其它方法实现重载 重载:属性重载与方法重 ...
- HDOJ 4389 X mod f(x)
数位DP........ X mod f(x) Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/ ...
- cf306 C. Divisibility by Eight(数学推导)
C. Divisibility by Eight time limit per test 2 seconds memory limit per test 256 megabytes input sta ...
- JAVA Io 缓冲输入输出流
java中提供带缓冲的输入输出流.在打开文件进行写入或读取操作时,都会加上缓冲,提高了IO读写性能. 1. BufferedInputStream 缓冲输入流 2. BufferedOutputStr ...