用Express简单创建一个Mock服务
Posted rosicky-707
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用Express简单创建一个Mock服务相关的知识,希望对你有一定的参考价值。
安装express:
1 npm install --save express
安装Mockjs:
1 npm install mockjs
建立MockServer.js文件:
1 let express = require(‘express‘); //引入express 2 let Mock = require(‘mockjs‘); //引入mock 3 4 let app = express(); //实例化express 5 6 app.use(function(req, res, next) 7 res.header("Access-Control-Allow-Origin", "*"); 8 res.header(‘Access-Control-Allow-Methods‘, ‘PUT, GET, POST, DELETE, OPTIONS‘); 9 res.header("Access-Control-Allow-Headers", "X-Requested-With"); 10 res.header(‘Access-Control-Allow-Headers‘, ‘Content-Type‘); 11 next(); 12 ); 13 14 app.use(‘/api/GetData‘,function(req, res) 15 console.log(‘收到请求,路径:‘ + req.url) 16 console.log(‘客户端地址:‘, req.socket.remoteAddress, req.socket.remotePort) 17 res.json(Mock.mock( 18 ‘status‘: 200, 19 ‘data|1-9‘:[ 20 ‘key|+1‘: 1, 21 ‘Title|1‘:[‘主题1‘, ‘主题2‘], 22 ‘Content|1‘: [‘内容1‘, ‘内容2‘, ‘内容3‘, ‘内容4‘, ‘内容5], 23 ‘Action|1‘: [‘操作1‘, ‘操作2‘, ‘操作3‘] 24 ] 25 )) 26 ) 27 28 app.listen(‘8085‘, () => 29 console.log(‘监听端口 8085‘) 30 )
启动:
1 node MockServer.js
以上是关于用Express简单创建一个Mock服务的主要内容,如果未能解决你的问题,请参考以下文章