nodejs+express4+jade快速搭建http服务

更新时间:2015-06-12 11:39:06点击次数:1554次

一, 概述

通过express搭建http服务。

1. express4

× express

× serve-favicon 处理favicon

× morgan 日志系统

× method-override 处理PUT/DELETE请求,目前没有用到

× express-session 处理session

× body-parser 处理post提交的body。

× multer 处理文件上传。

× errorhandler 错误处理

2. jade 模板引擎

3. easyui 前端架构

二, 功能:

1. 登录页面

2. 登录校验,校验是否登录,如果登录将用户信息保存至session。

3. 主页,使用easyui layout布局。

三, 代码分析:

1. server.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var methodOverride = require('method-override');
var session = require('express-session');
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');

// self define js library
var router = require("./server/router.js");

var app = express();

// all environments
app.set('port', process.env.PORT || 18080);
app.set('views', path.join(__dirname, 'jade'));
app.set('view engine', 'jade');
app.use(favicon(path.join(__dirname, 'static/favicon.ico')));
app.use(logger('dev'));
app.use(methodOverride());
app.use(session({ resave: true,
                  saveUninitialized: true,
                  secret: 'uwotm8' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());
app.use(express.static(path.join(__dirname, 'static'))); //静态页面地址

// development only
if ('development' == app.get('env')) {
  app.use(errorHandler());
}
// 注册url以及url handler
router.register(app);

app.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

2. router.js path注册页面

var url = require("url");
var merge = require("merge");

var router = {};
var serverConfig = require("../server.json");
// 指示是否启动登录校验。
var VALIDATE_LOGIN = true;

/**
 * string-function|object
 * function: see object handler
 * object {
 *      type: html(default) | json,
 *      method: get(default) | post
 *      handler: function(req, res)
 * }
 * @type {{/: indexController, /index.html: indexController, detail.html: {handler: detailController}}}
 */
var htmlPath = {
    "/": indexController,
    "/index.html": indexController,
    "/list.html" : listController
};
var codePath = {
    "NOT_LOGIN" : {
        code: -100,
        message: "当前用户未登录!"
    },
    "FAIL": {
        code: -1,
        message: "操作失败!"
    },
    "SUCCESS" : {
        code: 1,
        message: "操作成功!"
    },
    "LOGIN_SUCCESS" : {
        code: 100,
        message: "登录成功!"
    }
};

router.register = function(app){
    app.use(function(req, res, next){
        if(!VALIDATE_LOGIN){
            next();
        }
        else{
            var type = isIntercept(req);
            if(type == "json"){
                res.json(codePath["NOT_LOGIN"]);
            }
            else if(type=="html"){
                res.redirect("/login.html?url=" + encodeURIComponent(req.url))
            }
            else{
                next();
            }
        }
    });
    var key, value;
	for(key in htmlPath){
        value = htmlPath[key];
        if(typeof(value)=="function"){
            app.get(key, value);
        }
        else if(typeof(value)=="object" && typeof(value.handler)){
            if(value.method=="post"){
                app.post(key, value.handler);
            }
            else{
                app.get(key, value.handler);
            }
        }
    }

    app.get("/login.html", login1);
    app.post("/doLogin.html", login2);
};
function indexController(req, res){
    res.render("index", getServerConfig());
}
function listController(req, res){
    var obj = {message: req.param("message")};
    res.render("list", getServerConfig(obj));
}
function login1(req, res){
    res.render("login", getServerConfig());
}
function login2(req, res){
    var username = "", password = "";
    var ret = "";
    var obj = {};
    if(req.body){
        username = req.body.username;
        password = req.body.password;
        if(req.session){
            req.session.username = username;
            req.session.password = password;
        }
    }
    if(username && password){
        if(req.session){
            req.session.uid = username;
        }
        res.json(codePath["LOGIN_SUCCESS"])    
    }
    else{
        res.json(codePath["FAIL"]);
    }
}
function isIntercept(req){
    var pp = url.parse(req.url).pathname;
    var value = htmlPath[pp];
    if(value){
        if(req.session && req.session.uid){
            return "";
        }
        if(typeof(value)=="function"){
            return "html";
        }
        else if(typeof(value)=="object"){
            return value.type || "html";
        }
    }
    return "";
}
function getServerConfig(obj){
    return merge({}, {server: serverConfig}, obj);
}




module.exports = router;

四, 截图

nodejs+express4+jade快速搭建http服务

nodejs+express4+jade快速搭建http服务

nodejs+express4+jade快速搭建http服务


  • 项目经理 点击这里给我发消息
  • 项目经理 点击这里给我发消息
  • 项目经理 点击这里给我发消息
  • 项目经理 点击这里给我发消息