应用express mockjs模拟前端json数据接口

一、首先需要在项目安装express 1、cnpm install express --save-dev  2、cnpm install mockjs --save-dev

二、在项目根目录下新建prod.server.js

var express = require('express');
var Mock = require('mockjs');
var config = require('./config/index');
var port = process.env.PORT || config.build.port;
var app = express();



var apiRoutes = express.Router();
apiRoutes.all('/order',function(req,res){
    res.json(Mock.mock({
        "reason|1-10":[{
            "ORDERID|1-10":/[a-zA-Z1-9]/,
            "PKG_NUM|1-8":/[1-9]/,
            "HAS_REPORT":false,
            "ODSTATUS":"样本接收",
            "SEND_TIME":"@date",
            "HZNAME":"@name",
            "EXAMNAME":"原溯450"
        }]
    }))
});
app.use('/api', apiRoutes);

app.use(express.static('./dist'));

module.exports = app.listen(port, function (err) {
    if (err) {
        console.log(err);
        return
    }
    console.log('Listening at http://localhost:' + port + '\n');
});
期中 var config = require('./config/index'); 引用了config下的index.js 修改了port:9000字段为 9000
四、跑服务 node prod.server.js
五、http://localhost:9000/api/order/
  
{"reason":[{"ORDERID":"Q2UxI","PKG_NUM":"5377","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"2014-01-22","HZNAME":"Timothy Martin","EXAMNAME":"原溯450"},{"ORDERID":"B66KEKG","PKG_NUM":"9","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"1981-03-15","HZNAME":"Scott Wilson","EXAMNAME":"原溯450"},{"ORDERID":"EH8OLT","PKG_NUM":"786","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"1987-10-16","HZNAME":"Sharon Robinson","EXAMNAME":"原溯450"},{"ORDERID":"OpY7QBqLOn","PKG_NUM":"4885","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"2009-09-28","HZNAME":"Melissa White","EXAMNAME":"原溯450"},{"ORDERID":"CN","PKG_NUM":"33","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"1995-08-08","HZNAME":"Michael Lewis","EXAMNAME":"原溯450"},{"ORDERID":"OO1C","PKG_NUM":"78413","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"2013-08-31","HZNAME":"Susan Jones","EXAMNAME":"原溯450"},{"ORDERID":"UhM","PKG_NUM":"648748","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"2012-11-24","HZNAME":"Margaret Allen","EXAMNAME":"原溯450"},{"ORDERID":"nu","PKG_NUM":"726864","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"1976-10-09","HZNAME":"Maria Jackson","EXAMNAME":"原溯450"},{"ORDERID":"aXAP","PKG_NUM":"46","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"1971-03-25","HZNAME":"Joseph Clark","EXAMNAME":"原溯450"},{"ORDERID":"fsYs8II8","PKG_NUM":"738731","HAS_REPORT":false,"ODSTATUS":"样本接收","SEND_TIME":"2005-09-28","HZNAME":"Charles Thompson","EXAMNAME":"原溯450"}]}
 
   

这样就可以跑起来一个模拟数据接口的服务了。期中mockjs语法参考https://segmentfault.com/a/1190000003087224

 

转载于:https://www.cnblogs.com/junwu/p/6945922.html

你可能感兴趣的:(json,前端,ViewUI)