使用json-server来模拟REST API

vue项目需要从后端服务器获取json数据来渲染到页面上,使用json-server可以轻松搭建一个模拟数据的测试服务器。

json-servergithub地址为https://github.com/typicode/json-server

首先安装必要模块vue-resourcejson-server

npm install vue-resource --save
npm install json-server --save

vue-resource的配置不再赘述

json-server配置

// dev-server.js
var jsonServer = require('json-server')
var apiServer = jsonServer.create()
var apiRouter = jsonServer.router('db.json')
var middlewares = jsonServer.defaults()

apiServer.use(middlewares)
apiServer.use('/api', apiRouter)
apiServer.listen(port + 1, function () {
  console.log('JSON Server is running')
})

api地址代理到8081端口上

// config/index.js
dev:{
    ...
    proxyTable: {
      '/api/': 'http://localhost:8081/'
    },
    ...
}
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注