平時開發前端應用,若是沒有現成的後端接口調試,又要保證前端進度,該怎麼辦呢,固然辦法仍是不少的,不少大牛都分享過不少經驗,我也來講說我經常使用的方法。前端
把本地數據放到程序指定目錄,發起http請求時候,用get請求到這個目錄中指定文件node
以jquery的ajax爲例:mysql
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參數,參數值任意,就能夠調用本地數據,這個方法只能讀取文件,內容是比較死板的,下面就說說另一種方法jquery
用nodejs弄個web服務器是灰常簡單的,這也是不少開發者都會用nodejs作箇中轉服務,下面介紹下怎麼搭建測試服務git
app.jsgithub
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.jsweb
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.jsajax
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.jsonsql
[{ "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開發的服務端mongodb
完整示例: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/