前端使用express + express-generator + nodemon + mockjs高效mock接口数据

  1. 安装
  • npm install express -g (node express框架)
  • npm install express-generator -g (快速搭建express项目)
  • npm install nodemon -g (实现后台热更新,修改代码后自动刷新接口)
  • npm install mockjs (mock库)
  1. 搭建
  • 指定目录下,命令行输入express mockserver,生成名为mockserver的项目
  • cd 到 mockserver目录
  • mockserver根目录下,执行npm install安装依赖
  • mockserver根目录下,执行npm start,启动server,浏览器打开localhost:3000即可访问服务器
  1. 修改文件
  • app.js文件,代码var app = express();下方插入:
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*'); //访问控制允许来源:所有
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); //访问控制允许报头 X-Requested-With: xhr请求
res.header('Access-Control-Allow-Metheds', 'PUT, POST, GET, DELETE, OPTIONS'); //访问控制允许方法
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
  • 控制路由的文件夹routes下,新建list.js
var express = require('express');
var router = express.Router();
var Mock = require('mockjs');
var Random = Mock.Random;

router.get('/', function (req, res, next) {
var data =Mock.mock({
  'list|2':[{
    'id|+1':1,
    'goods_id':Random.id(),
    'goods_name':Random.cword(),
    'img':Random.image(),
    'stock':Random.integer(),
    'imgs|1':['大号','磁盘占用超过阈值'],
    'warn_level|1-3':[Random.image()],
    'sku|1':['大号','小号'],
    'create_at':Random.datetime(),

  }]
});

res.send({
  type:'success',
  status:200,
  data: data.list
})
})
module.exports = router;

  • app.js中添加list路由
app.use('/list', listRouter)

最终app.js:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var listRouter = require('./routes/list');

var app = express();
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*'); //访问控制允许来源:所有
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); //访问控制允许报头 X-Requested-With: xhr请求
res.header('Access-Control-Allow-Metheds', 'PUT, POST, GET, DELETE, OPTIONS'); //访问控制允许方法
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/list', listRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;
  1. 重新npm start,访问localhost:3000/list即可获取到mock数据(端口号可在bin/www文件中修改)
    想要修改代码后不重新npm start,实现接口自动刷新,就需要用到nodemon了
  2. 在mockserver根目录创建 nodemon.json 文件
{
"restartable": "rs",
"ignore": [
  ".git",
  ".svn",
  "node_modules/**/node_modules"
],
"verbose": true,
"execMap": {
  "js": "node --harmony"
},
"watch": [

],
"env": {
  "NODE_ENV": "development"
},
"ext": "js json njk css js "
}
  1. 根目录package.json的scripts中添加"dev": "nodemon ./bin/www"
"scripts": {
  "start": "node ./bin/www",
  "dev": "nodemon ./bin/www"
}
  1. 执行npm run dev,之后修改代码即可实现热刷新

你可能感兴趣的:(前端使用express + express-generator + nodemon + mockjs高效mock接口数据)