express+mockjs搭建数据服务

Posted HeavyShell

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了express+mockjs搭建数据服务相关的知识,希望对你有一定的参考价值。

前端开发的朋友们,不免会有要模拟假数据的时候,当然你的项目中有模拟数据的配置(如mock)则更好;
但是当仅仅就是想起个服务端,模拟点假数据便于开发调用,那么今天就给大家介绍一种快捷有效的方法:
express+mockjs搭建数据服务

现只模拟一下四个接口供参考:

http://127.0.0.1:30001/api/users  get请求  列表数据
http://127.0.0.1:30001/api/users/123456  get请求 单条数据
http://127.0.0.1:30001/api/users  post请求  新增数据
http://127.0.0.1:30001/api/users/123456  put请求 修改单条数据
http://127.0.0.1:30001/api/users/123456  delete请求 删除单条数据

话不多说,上货

1新建目录demo mkdir demo 进入 cd demo
2创建package.json文件,写入:


  "name": "express-mock",
  "version": "1.0.0",
  "description": "express+mockjs搭建数据服务",
  "main": "index.js",
  "dependencies": 
    "body-parser": "^1.18.3",
    "express": "^4.16.3",
    "mockjs": "^1.0.1-beta3"
  ,
  "devDependencies": ,
  "scripts": 
    "start": "node index"
  ,
  "author": "Heavy",
  "license": "ISC"

3创建index.js文件,写入:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: false ));

require('./mock/user')(app); //user数据

var server = app.listen(30001, function () 
  var host = server.address().address;
  var port = server.address().port;

  console.log('App listening at http://%s:%s', host, port);
);

4新建目录mock mkdir mock 进入 cd mock
(1)mock目录下创建user.js文件,写入:

let Mock = require('mockjs'); 

let db=Mock.mock(
	'data|50-100':[
		id:'@id',
		name:'@cname',
		'age|18-100':1,
		create_time:'@datetime',
		avatar:function() 
			return Mock.Random.image('100x100',Mock.Random.color(),Mock.Random.string('upper', 3))
		,
		address:'@county(true)',
		email:'@email',
		love_color:'@color',
		'description':'@csentence(20, 40)'
	]
);


module.exports = function (app) 

	//获取列表数据
	app.get('/api/users', function (req, res) 
		
		let pagesize=req.headers&&req.headers.pagesize;
		let current=req.headers&&req.headers.current;
	
		res.header('total', db.data.length);
		res.status(200).json(db.data.slice((current-1)*pagesize,current*pagesize));
		
	);

	//获取单个详情
	app.get('/api/users/:id', function (req, res) 
		
		let id=req.params.id;
        let info=
            data:
        ;
        db.data.map(item=>
            if(item.id==id)
                info.data=item
            
        )
        
        res.status(200).json(info);
		
	);

	//新增一条数据post
	app.post('/api/users', function (req, res) 
		
		let user=req.body;
        user.id=Mock.mock('@id');
        db.data.push(user);
        
        res.status(200).json(user);
		
	);

	//修改一条数据put
	app.put('/api/users/:id', function (req, res) 
		
		let id=req.params.id;
		let user=req.body;
        user.id=id;
        db.data.map((item,index)=>
            if(item.id==id)
                db.data[index]=user;
            
        )
        
        res.status(200).json(user);
		
	);

	//删除一条数据delete
	app.delete('/api/users/:id', function (req, res) 
		
		let id=req.params.id;
        db.data.map((item,index)=>
            if(item.id==id)
                db.data.splice(index,1);
            
        )
        
        res.status(200).json(id:id);
		
	);

(2)返回主目录demo cd ../

 

5 yarn install 或npm(cnpm) install 安装包


6 yarn start 启动服务,打印‘App listening at http://:::30001’,即OK了。

此时访问:http://127.0.0.1:30001/api/users 看,数据出来了,postman试一下:

同理,对应增删改查均OK!!!

若要支持跨域访问,可修改index.js如下:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: false ));

//跨域访问,允许接受跨域请求
app.all('*', function(req, res, next) 
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "*");
	res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
	res.header("X-Powered-By",' 3.2.1')
	res.header("Content-Type", "application/json;charset=utf-8");
	next();
)

require('./mock/user')(app); //user数据
require('./mock/contract')(app); //contract数据
require('./mock/meeting')(app); //meeting数据
require('./mock/invoice')(app); //invoice数据
require('./mock/enterprise')(app); //enterprise数据
require('./mock/fileresource')(app); //fileresource数据
require('./mock/acs_api')(app); //fileresource数据
require('./mock/smartplugs')(app); //smartplugs数据
require('./mock/cipicture')(app); //cipicture数据,设备外观
require('./mock/ticketTopo')(app); //ticketTopo数据,事件绑定拓扑
require('./mock/notes')(app); //notes数据,白板笔记
require('./mock/interfaces')(app); //interfaces数据,主机端口新版
require('./mock/hostProblems')(app); //hostProblems数据,主机监控信息

var server = app.listen(30001, function () 
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
);

 

推荐参考:

http://mockjs.com/examples.html

http://www.expressjs.com.cn/

以上是关于express+mockjs搭建数据服务的主要内容,如果未能解决你的问题,请参考以下文章

通过mockjs来制作假数据

使用json-server与Mockjs搭建模拟服务

用Express简单创建一个Mock服务

改造vue-cli,使用mockjs搭建mock server

在vue-cli环境下模拟数据接口及如何应用mockjs

vite+mockjs+vite-plugin-mock 搭建mock环境