json-server模拟接口获取mock数据

转载: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展示内容一致,表示代理设置成功

原文地址:https://www.cnblogs.com/ceshi2016/p/7884099.html