日常平凡开辟前端运用,假如没有现成的后端接口调试,又要保证前端进度,该怎样办呢,固然要领照样许多的,许多大牛都分享过许多履历,我也来说说我经常使用的要领。
要求当地数据文件
把当地数据放到顺序指定目次,提议http要求时刻,用get要求到这个目次中指定文件
以jquery的ajax为例:
postRequest: function(model, async) {
if(!model) {
return null;
}
if(Common.urlParams.d) {
url = "../data/" + model.method + ".json";
model.type = "GET";
} else {
url = service-api-path + model.method; //service-api-path是后端接口大众地点
}
return $.ajax({
async: (async == undefined || async) ? true : false,
url: url,
type: model.type,
dataType: "json",
timeout: 30000,
data: model.params,
beforeSend: function(x, settings) {
//todo..
},
complete: function(x, status) {
//todo..
},
error: function(x, h, r) {
//todo
}
});
}
这个例子是在接见页面的时刻在链接中增加一个d参数,参数值恣意,就能够挪用当地数据,这个要领只能读取文件,内容是比较枯燥的,下面就说说别的一种要领
用nodejs+express
用nodejs弄个web效劳器是灰常简朴的,这也是许多开辟者都会用nodejs做个中转效劳,下面引见下怎样搭建测试效劳
app.js
var path = require('path'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
autoRoutes = require('express-auto-routes'),
server = require('./server');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
var routes = autoRoutes(app);
app.use(server);
app.use(function(req, res, next) {
res.status(404);
next({ _code: 404, _msg: 'Page not found' });
});
app.use(function(err, req, res, next) {
console.error(err);
if (err._status) res.status(err._status);
res.json({
_code: err._code || 1,
_msg: err._msg || err
});
});
var server;
if (!module.parent) {
var PORT = 8989;
console.log('[INFO] Msg board RESTful API listening at localhost:%s', PORT);
server = app.listen(PORT);
} else {
module.exports = app;
}
server.js
var dbm = require('./dbm'),
_ = require("lodash");
module.exports = function(req, res, next) {
let data = [],
params = {},
url = req.originalUrl,
db = new dbm(`./db/${url.slice(url.lastIndexOf('/') + 1, url.length)}.json`).read()
data = _filter(db, req.body)
res.json({ timestamp: new Date().getTime(), msg: "查询胜利", isSuccess: 0, data: data })
}
const _filter = (db, obj) => {
if (!obj) return
return _.filter(db, o => { return obj.dateTime == o.dateTime })
}
dbm.js
var fs = require('fs'),
path = require('path');
function dbm(relativePath) {
this.db = path.resolve(__dirname, relativePath);
}
dbm.prototype._isAvailable = function() {
return fs.existsSync(this.db);
};
dbm.prototype.read = function() {
if (!this._isAvailable()) return null;
var contentInStr = fs.readFileSync(this.db, 'utf-8'),
content;
try {
content = JSON.parse(contentInStr);
} catch (e) {
//this.delDb();
console.error('[ERR] JSON.parse failed, deleted ' + this.db);
}
return content || null;
};
dbm.prototype.save = function(data) {
var stringToSave = JSON.stringify(data);
if (!stringToSave) return;
fs.writeFileSync(this.db, stringToSave, 'utf-8');
};
dbm.prototype.delDb = function() {
try {
fs.unlinkSync(this.db);
} catch (e) {
console.error('DB file does not exist');
}
};
module.exports = dbm;
demo.json
[{
"name": "jack",
"age": 18,
"id": "124443",
"dateTime": "20170101"
},
{
"name": "tom",
"age": 21,
"id": "1232323",
"dateTime": "20170103"
},
{
"name": "alix",
"age": 22,
"id": "123232323",
"dateTime": "20170102"
}
]
致此,效劳器基础完事了,json文件寄存内容遵照mongodb或许根据mysql数据纪录来就行了,引入lodash库支配数组完成增编削查完全不在话下,固然也能够拓展成为真正的效劳器嘛,毕竟许多项目直接就是nodejs开辟的效劳端
完全示例:https://github.com/dawnyu/node-simple-server.git
原发:http://dawns.me/2017/05/05/%E7%94%A8nodejs+express%E6%90%AD%E5%BB%BA%E5%89%8D%E7%AB%AF%E6%B5%8B%E8%AF%95%E6%9C%8D%E5%8A%A1%E7%AB%AF/