express
基于 Node.js 平台,快速、开放、极简的 web 开发框架。
源代码:
https://github.com/tangxuelong/expressWeb
1.启动 httpServer index
var express = require('express');
var app = express();
// respond with "hello world" when a GET request is made to the homepage
app.all('/', function timeLog(req, res, next) {
console.log('Time:',new Date().getTime());
});
var product = require('./router/product');
app.use('/product', product);
var port = '8889';
app.listen(port);
console.info('server start successful!\nport is '+port);
2.创建路由 router
var express = require('express');
var router = express.Router();
var commonUtil = require('./commonUtil');
// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
router.all('/',function(req,res){
res.send('this is h5 be product api,please choose operation:/add /delete /select /modify');
})
/*@params
channel
addkey
*/
// 添加
router.all('/addOrModify', function(req, res) {
var data = getChannelData(req,res)[0];
var channel = getChannelData(req,res)[1];
for(key in req.query){
data[key] = req.query[key];
}
commonUtil.readFile(channel);
commonUtil.writeFile(channel,data);
res.send(commonUtil.buildSucJson(data));
});
/*
@params
channel
delkey
*/
// 删除
router.all('/delete', function(req, res) {
var data = getChannelData(req,res)[0];
var channel = getChannelData(req,res)[1];
/* 校验delKey不为空*/
if(!req.query['delKey']){
res.send(commonUtil.buildErrJson("","delKey 为必需参数!"));
}
for(key in data){
if(key = req.query['delKey']){
delete data[key];
}
}
commonUtil.writeFile(channel,data);
res.send(data);
});
// 查询
router.all('/select', function(req, res) {
var data = getChannelData(req,res)[0];
var channel = getChannelData(req,res)[1];
res.send(data);
});
// 获取渠道配置信息
function getChannelData(req,res){
// 找到product.json中的对应配置项 进行修改
console.log(typeof(req.query['channel']));
if(typeof(req.query['channel'])=='undefined'){
res.send(commonUtil.buildErrJson("","请配置渠道!"));
}
var channel = req.query['channel'];
try{
var data = require('../data/'+channel);
}
catch(e){
res.send(commonUtil.buildErrJson("","没有对应的渠道!"));
}
if(typeof(data)=='undefined'){
data = {};
}
console.log('请求的参数:'+req.query);
return [data,channel];
}
module.exports = router;
3.工具方法 commonUtil
module.exports = {
readFile:function(dataFileName){
console.log(require('fs').readFile('./data/'+dataFileName+'.js',function(err,data){
if(err){
throw err;
}
return (data.toString());
}));
},
writeFile:function(dataFileName,data){
require('fs').writeFile('./data/'+dataFileName+'.js','module.exports = '+JSON.stringify(data),function(err){
throw err;
});
},
buildErrJson:function(data,msg){
return JSON.stringify({"code":-1,"resp":data,"msg":msg});
},
buildSucJson:function(data,msg){
return JSON.stringify({"code":0,"resp":data,"msg":msg?msg:"请求成功"});
}
}
- 数据 data
module.exports = {"400":"12345","channel":"meizuh5"}
参考