一個NodeJS寫的基於MVC的伺服器

來源:互聯網
上載者:User

標籤:

目前實現了靜態檔案下載、根據地址導航到控制器相應的控制器方法,但視圖模版功能目前還未實現。

 

伺服器代碼(httpserver.js):

var http = require("http"),     url = require("url"),     path = require("path"),    fs = require("fs"),    getContentType=function(type){        var type=type.indexOf(".")===0 ? type.substr(1) : type,            defType="application/octet-stream",            types={                html:"text/html",                js:"text/javascript",                css:"text/css",                gif:"image/gif",                jpg:"image/jpeg",                png:"image/png",            };        return typeof(types[type])!="undefined" ? types[type] : defType;    };http.createServer(function(req, res) {    var pathname=url.parse(req.url).pathname;    if(pathname=="/"){        pathname+="index.html";    }    pathname=__dirname+pathname;    console.log(req.url);    if(req.url.match(/^\/controller\//) || req.url.match(/^\/data\//)){ //禁止訪問目錄        res.writeHead(404, {"Content-Type" : "text/html"});    }else if(req.url.match(/^\/\w+\/\w+(\?.*)?$/)){ //控制器輸出        var u=url.parse(req.url),            ca=u.pathname.substr(1).split("/"),            c=ca[0],a=ca[1],            cpath=__dirname + "/controller/"+c+".js",            controller;        if(fs.existsSync(cpath)){            res.writeHead(200, {"Content-Type" : getContentType("html")});            controller=require(cpath);            if(typeof(controller[a])!="undefined"){                controller[a](res,u);            }            //delete require.cache[cpath]; //是否清空指令碼緩衝        }else{            res.writeHead(200, {"Content-Type" : getContentType("html")});            res.end(path+" not exists!");        }    }else if(fs.existsSync(pathname)){//靜態檔案輸出        res.writeHead(200, {"Content-Type" : getContentType(path.extname(pathname))});        fs.readFile(pathname, function(err, data) {            res.end(data);        });    }else{        res.writeHead(404, {                "Content-Type" : getContentType("html")        });        res.end("<h1>404 Not Found</h1>");    }}).listen(8080, "127.0.0.1");console.log("Server running at http://127.0.0.1:8080/");

 

控制器代碼(controller/project.js):

var tm=1,    mysql=require("mysql"),    conn = mysql.createConnection({            host: ‘127.0.0.1‘,            user: ‘root‘,            password: ‘123456‘,            database:‘dbname‘,            port: 3306        });conn.connect();var project={    show:function(res,url){        var paras={},tb="user";        console.log(url.query);        if(typeof(url.query)=="string"){            var ps=url.query.split("&"),pss;            for(var k in ps){                pss=ps[k].split("=");                paras[pss[0]]=pss[1];            }        }        res.write((tm++)+"<br/>");        conn.query(            ‘SELECT * from prefx_‘+(typeof(paras.tb)!="undefined" ? paras.tb : tb )+‘ limit 0,3‘,             function(err, results, fields){                var field="",str="",fds=[];                if (results) {                    for(var k in fields){                        fds.push(fields[k][‘name‘]);                    }                    for ( var i = 0; i < results.length; i++) {                        str="";                        for(var k in fds){                            str+=results[i][fds[k]]+"\t";                        }                        res.write(str+"<br/>");                    }                }                res.end("<br/>"+(new Date()).getTime());            }        );    }}module.exports=project;

 

網站目錄結構如下:

例如訪問:http://127.0.0.1:8080/project/show,則訪問project控制器中show方法

一個NodeJS寫的基於MVC的伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.