转载:http://blog.csdn.net/stevennest/article/details/76167343

  1. 安装json-server 
    运行以下命令 
    cnpm install json-server –save
  2. 参考官方文档修改dev-server.js 
    文档地址:json-server官方文档

    2.1 修改dev-server.js

const jsonServer = require('json-server')
const aipServer = jsonServer.create()
const apiRouter = jsonServer.router('db.json') //此处的db.json是与package.json在同一目录下
const middlewares = jsonServer.defaults() aipServer.use(middlewares)
aipServer.use(apiRouter)
aipServer.listen(port + 1, () => {
console.log('JSON Server is running')
})

如下图所示 

2.2 修改db.json文件 
在db.json添加以下内容

{
"getList":[
{
"id":1,
"title":"title1",
"content":"content1"
},
{
"id":2,
"title":"title2",
"content":"content2"
},
{
"id":3,
"title":"title3",
"content":"content3"
}
]
}

2.3 在浏览器打开网址验证json-server是否启动成功 
在浏览器打开以下网址:http://localhost:8081/ 
成功打开地址后证明json-server安装成功,打开地址后可以看到db.json中的接口方法“getList”,点击“getList”,返回getList数据,证明可以成功调用mock数据。

  1. 使用代理访问mock数据 
    我们在项目里访问什么路径会到json-server,这需要我们做一个代理。 
    4.1 修改 config文件夹中的index.js 
    修改index.js文件,在 dev 对象中的 proxyTable 设置以下代理对象
   {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
}
}

如下图所示

   dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
}
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}

4.2 在浏览器中访问以下地址 
http://localhost:8080/api/ 
页面展示内容和http://localhost:8081展示内容一致,表示代理设置成功

最新文章

  1. thinkphp3.2.3中U()方法和redirect()方法区别
  2. linux shell 流程控制(条件if,循环【for,while】,选择【case】语句实例 --转载
  3. 在Web.config中注册自定义控件
  4. VS 创建 使用C++ 静态类库(Dll)
  5. Xcode6中怎么添加空工程模板
  6. 结构-行为-样式-css&html横纵居中最佳实践
  7. redis源码分析之事务Transaction(上)
  8. PHP 字符串转 bigint 型md5
  9. js的内置对象
  10. Perl IO:read()函数
  11. 【Mybatis】使用Mybatis-Generator自动生成entity、dao、mapping
  12. Nginx启动,证书报错SSL_CTX_use_PrivateKey_file.....
  13. 某mac最简单调节亮度
  14. jQuery-4.动画篇---jQuery核心
  15. Deep Learning Tutorial - Multilayer perceptron
  16. python修改hosts
  17. go-无法下载websocket的问题
  18. 国密SM3算法在linux和windows平台结果不一致问题
  19. rayleighchan实现瑞利多径衰落信
  20. 【spring mvc】基础概念

热门文章

  1. Fix error of "you have been logged on with a temporary profile"
  2. CSS清除浮动常用方法小结 CSS clear both {overflow:auto;zoom:1;}
  3. HDU1541 经典树状数组
  4. 杭电oj2072
  5. 一篇不错的v4l2入门文档【转】
  6. windows下xampp安装PHP的pthreads多线程扩展
  7. 51nod 1873 初中的算术【Java BigDecimal/高精度小数】
  8. python 字符串最长公共前缀
  9. UVA——11988 Broken Keyboard (a.k.a. Beiju Text)
  10. HDU 4815 Little Tiger vs. Deep Monkey 2013 长春现场赛C题