1. 程式人生 > >【HAVENT原創】Node Express API 通用配置

【HAVENT原創】Node Express API 通用配置

urn tar xss pub have case dev 全部 ==

啟動文件 /app.js:

var express = require(‘express‘);
var bodyParser = require(‘body-parser‘);
var proxy = require(‘http-proxy-middleware‘);
var path = require(‘path‘);

var index = require(‘./routes/index‘);
var data = require(‘./routes/data‘);

var app = express();

/* 設置靜態目錄 */
app.use(express.static(‘src‘));

/* 啟用反向代理 */ var options = { target: ‘http://localhost:8080/h5‘, // 目標主機 changeOrigin: true, //secure: false, // ws: true, // pathRewrite: { // ‘^/api‘ : ‘/h5/api‘ // } }; var apiProxy = proxy(options); // 開啟代理功能,並加載配置 app.use(‘/api‘, apiProxy); // 對地址為’/‘的請求全部轉發 // Node Express API 路由配置 app.use(‘/‘, index); app.use(
‘/data‘, data); // // catch 404 and forward to error handler // app.use(function(req, res, next) { // var err = new Error(‘Not Found‘); // err.status = 404; // next(err); // }); // // error handler // app.use(function(err, req, res, next) { // // set locals, only providing error in development // res.locals.message = err.message;
// res.locals.error = req.app.get(‘env‘) === ‘development‘ ? err : {}; // // // render the error page // res.status(err.status || 500); // res.render(‘error‘); // }); /* json 輸出支持, 啟動服務 */ app.use(bodyParser.json()); app.listen(7788); var url = "http://localhost:7788"; console.log(‘listen: ‘ + url); /* 啟動瀏覽器訪問站點 */ var child_process = require("child_process"); var cmd = ‘start ‘ + url; if(process.platform == ‘linux‘){ cmd = ‘xdg-open ‘; }else if(process.platform == ‘darwin‘){ cmd = ‘open ‘; } // else{ // process.platform == ‘win32‘ // cmd = ‘start "%ProgramFiles%\Internet Explorer\iexplore.exe"‘; // } child_process.exec(cmd + ‘ "‘+url + ‘"‘); //child_process.exec(cmd + url);

路由配置 /routes/index.js

var express = require(‘express‘);
var router = express.Router();


/* GET home page data. */
router.get(‘/‘, function(req, res, next) {
    res.send({ title: ‘首頁‘ });
});

router.get(‘/login‘, function(req, res, next) {
    res.send({ title: ‘登錄‘ });
});


module.exports = router;

路由配置 /routes/data.js

var express = require(‘express‘);
var router = express.Router();
var fs = require(‘fs‘);
var PATH = ‘./public/data/‘;

//讀取數據模塊,供客戶端調用
//查詢接口,token校驗
//公共接口,無需校驗
//data/read?type=it
//data/read?type=it.json
router.get(‘/read‘, function(req, res, next) {
    var type = req.param(‘type‘) || "";
    fs.readFile(PATH + type + ‘.json‘, function (err, data){
        if(err){
            return res.send({
                success: false,
                message: ‘讀取文件異常‘
            });
        }
        var COUNT = 50;
        // TODO: try{}catch(){}
        var obj =[];
        try{
            obj = JSON.parse(data.toString());
        }catch(e){
            obj = [];
        }
        if(obj.length > COUNT){
            obj = obj.slice(0, COUNT);
        }
        return res.send({
            success: true,
            data:obj
        });
    });
});


// 數據存儲模塊——後臺開發使用
router.post(‘/write‘,function(req, res, next){
    if(!req.cookies.user){
        return res.render(‘login‘,{});
    }
    // 文件名
    var type = req.param(‘type‘) || "";
    // 關鍵字段
    var url = req.param(‘url‘) || ‘‘;
    var title = req.param(‘title‘) || ‘‘;
    var img = req.param(‘img‘) || ‘‘;
    if(!type || !url || !title || !img){
        return res.send({
            success: false,
            message:‘提交的字段不全‘
        });
    }
    //1)讀取文件
    var filePath = PATH + type + ‘.json‘;
    fs.readFile(filePath, function(err, data){
        if(err){
            return res.send({
                success: false,
                message: ‘讀取數據失敗‘
            });
        }
        var arr = JSON.parse(data.toString());
        //代表每一條記錄
        var obj = {
            img: img,
            url: url,
            title: title,
            id: guidGenerate(),
            time: new Date()
        };
        arr.splice(0, 0, obj);
        //2)寫入文件
        var newData = JSON.stringify(arr);
        fs.writeFile(filePath, newData, function(err){
            if(err){
                return res.send({
                    status:0,
                    info: ‘寫入文件失敗‘
                });
            }
            return res.send({
                success: true,
                message: obj
            });
        });
    });
});

//閱讀模塊寫入接口 後臺開發使用
router.post(‘/write_config‘, function(req, res, next){
    if(!req.cookies.user){
        return res.render(‘login‘,{});
    }
    //TODO:後期進行提交數據的驗證
    //防xss攻擊 xss
    // npm install xss
    // require(‘xss‘)
    // var str = xss(name);
    var data = req.body.data;
    //TODO : try catch
    var obj = JSON.parse(data);
    var newData = JSON.stringify(obj);

    // 寫入
    fs.writeFile(PATH + ‘config.json‘,newData, function(err, data){
        if(err){
            return res.send({
                success: false,
                message: ‘寫入數據失敗‘
            });
        }
        return res.send({
            success: true,
            message:‘數據寫入成功‘,
            data:newData
        })
    })
});

//登錄接口
router.post(‘/login‘, function(req, res, next){
    //用戶名、密碼、驗證碼
    var username = req.body.username;
    var password = req.body.password;

    //TODO :對用戶名、密碼進行校驗
    //xss處理、判空

    //密碼加密 md5(md5(password + ‘隨機字符串‘))
    //密碼需要加密-> 可以寫入JSON文件
    if(username === ‘admin‘ && password === ‘123456‘){
        res.cookie(‘user‘,username);
        return res.send({
            success: true
        });
    }

    return res.send({
        success: false,
        message: ‘登錄失敗‘
    });
});

// guid
function guidGenerate() {
    return ‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx‘.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
            v = c == ‘x‘ ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    }).toUpperCase();
}

module.exports = router;

【HAVENT原創】Node Express API 通用配置