express模拟mock数据

来源:互联网 发布:女性就业歧视数据 编辑:程序博客网 时间:2024/05/01 02:54

1. 安装body-parser

运行以下命令

cnpm install body-parser –save

2. 把以下内容覆盖掉原来的dev-server.js

var config = require('../config')if (!process.env.NODE_ENV) process.env.NODE_ENV = config.dev.envvar path = require('path')var express = require('express')var webpack = require('webpack')var opn = require('opn')var proxyMiddleware = require('http-proxy-middleware')var webpackConfig = require('./webpack.dev.conf')// default port where dev server listens for incoming trafficvar port = process.env.PORT || config.dev.port// Define HTTP proxies to your custom API backend// https://github.com/chimurai/http-proxy-middlewarevar proxyTable = config.dev.proxyTablevar app = express()var compiler = webpack(webpackConfig)var devMiddleware = require('webpack-dev-middleware')(compiler, {  publicPath: webpackConfig.output.publicPath,  stats: {    colors: true,    chunks: false  }})var hotMiddleware = require('webpack-hot-middleware')(compiler)// force page reload when html-webpack-plugin template changescompiler.plugin('compilation', function (compilation) {  compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {    hotMiddleware.publish({ action: 'reload' })    cb()  })})// proxy api requestsObject.keys(proxyTable).forEach(function (context) {  var options = proxyTable[context]  if (typeof options === 'string') {    options = { target: options }  }  app.use(proxyMiddleware(context, options))})// handle fallback for HTML5 history APIapp.use(require('connect-history-api-fallback')())// serve webpack bundle outputapp.use(devMiddleware)// enable hot-reload and state-preserving// compilation error displayapp.use(hotMiddleware)// serve pure static assetsvar staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)app.use(staticPath, express.static('./static'))var apiServer = express()var bodyParser = require('body-parser')apiServer.use(bodyParser.urlencoded({ extended: true }))apiServer.use(bodyParser.json())var apiRouter = express.Router()var fs = require('fs')apiRouter.route('/:apiName').all(function (req, res) {  fs.readFile('./db.json', 'utf8', function (err, data) {    if (err) throw err    var data = JSON.parse(data)    if (data[req.params.apiName]) {      res.json(data[req.params.apiName])      }    else {      res.send('no such api name')    }  })})apiServer.use('/api', apiRouter);apiServer.listen(port + 1, function (err) {  if (err) {    console.log(err)    return  }  console.log('Listening at http://localhost:' + (port + 1) + '\n')})module.exports = app.listen(port, function (err) {  if (err) {    console.log(err)    return  }  var uri = 'http://localhost:' + port  console.log('Listening at ' + uri + '\n')  opn(uri)})

3. 新建db.json与package.json在同一目录下

4. 把以下内容拷贝到package.json

{  "getNewsList": [    {      "id": 1,      "title": "新闻条目1新闻条目1新闻条目1新闻条目1",      "url": "http://starcraft.com"    },    {      "id": 2,      "title": "新闻条目2新闻条目2新闻条目2新闻条目2",      "url": "http://warcraft.com"    },    {      "id": 3,      "title": "新闻条3新闻条3新闻条3",      "url": "http://overwatch.com"    },    {      "id": 4,      "title": "新闻条4广告发布",      "url": "http://hearstone.com"    }  ],  "login": {    "username": "yudongdong",    "userId": 123123  },  "getPrice": {    "amount": 678  },  "createOrder": {    "orderId": "6djk979"  },  "getOrderList": {    "list": [      {        "orderId": "ddj123",        "product": "数据统计",        "version": "高级版",        "period": "1年",        "buyNum": 2,        "date": "2016-10-10",        "amount": "500元"      },      {        "orderId": "yuj583",        "product": "流量分析",        "version": "户外版",        "period": "3个月",        "buyNum": 1,        "date": "2016-5-2",        "amount": "2200元"      },      {        "orderId": "pmd201",        "product": "广告发布",        "version": "商铺版",        "period": "3年",        "buyNum": 12,        "date": "2016-8-3",        "amount": "7890元"      }    ]  }}

5. 访问http://localhost:8081/api/getNewsList返回以下json证明express启用成功

    {      "id": 1,      "title": "新闻条目1新闻条目1新闻条目1新闻条目1",      "url": "http://starcraft.com"    }
原创粉丝点击