3

平时开发前端应用,如果没有现成的后端接口调试,又要保证前端进度,该怎么办呢,当然办法还是很多的,很多大牛都分享过很多经验,我也来说说我常用的方法。

请求本地数据文件

把本地数据放到程序指定目录,发起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/


千年老妖
289 声望9 粉丝

10多年开发经验,如何度过35岁危机?