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

2021-04-24 15:28

阅读:414

标签:cti   cat   验证码   -o   time   obj   验证   存储   secure   

启动文件 /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 通用配置

标签:cti   cat   验证码   -o   time   obj   验证   存储   secure   

原文地址:http://www.cnblogs.com/HAVENT/p/7943694.html


评论


亲,登录后才可以留言!