环境配置

这里需要用到json-server和mockjs模拟插件。

json-server: https://github.com/typicode/json-server
mockjs: http://mockjs.com/

安装

npm install json-server –save-dev
npm install mockjs –save-dev

mock目录结构

这里写图片描述

db.js文件

// mock框架,这里demo暂时没用到
var Mock = require('mockjs');

var apiUser = require('./modules/user.js');
var apiGoods = require('./modules/goods.js');

module.exports = {
    login: apiUser.login,
    goodsList: apiGoods.goodsList
}

routes.js文件

const routes = {
    "/user/login": "/login",
    "/goods/list": "/goodsList"
}

module.exports = routes;

server.js文件

const jsonServer = require('json-server');
const db = require('./db.js');
const routes = require('./routes.js');

const port = 3000;

const server = jsonServer.create()
const router = jsonServer.router(db)
const middlewares = jsonServer.defaults()
const rewriter = jsonServer.rewriter(routes)

server.use(middlewares)

// 将 POST 请求转为 GET
server.use((request, res, next) => {
    request.method = 'GET';
    next();
});

server.use(rewriter)  // 注意:rewriter 的设置一定要在 router 设置之前
server.use(router)

server.listen(port, () => {
    console.log(`open mock server at http://localhost:${port}`);
})

user.js文件


function login(config) {
    // 模拟数据
    let result = {
        code: 200,
        data: null,
        msg: '获取成功',
        time: new Date()
    }

    result.data = { userName: "hello", mobile: "13888888888" };
    return result;
}

module.exports = {
    login: login()
}

goods.js文件


function goodsList(config) {
    // 模拟数据
    let result = {
        "status": "0",
        "result": [
            {
                "productId": "10001",
                "productName": "小米6",
                "prodcutPrice": "2499",
                "prodcutImg": "mi6.jpg"
            },
            {
                "productId": "10002",
                "productName": "小米笔记本",
                "prodcutPrice": "3999",
                "prodcutImg": "minote.jpg"
            }
        ]
    };
    return result;
}

module.exports = {
    goodsList: goodsList()
}

配置请求代理

在/config/index.js中添加如下

module.exports = {
  dev: {
    proxyTable: {
      '/mock': {
        target: 'http://localhost:3000',   // 需要请求的地址
        changeOrigin: true,  // 是否跨域
        pathRewrite: {
          '^/mock': '/'  // 替换target中的请求地址,例如请求的时候把'/login'换成'/mock/login'
      }
    },
    }
}

配置package.json

这里由于涉及到一个终端开启两个端口的服务,所以需要用到concurrently,先安装concurrently。

npm install concurrently –save-dev

在package.json中添加如下脚本

  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "node build/build.js",
    "mock-server": "node ./src/mock/server.js",
    "mock-dev": "concurrently \"npm run dev\" \"npm run mock-server\""
  },

运行项目

npm run mock-dev

运行成功后就可以请求模拟数据了。

接口请求地址

http://localhost:3000/login
http://localhost:3000/goodsList

请求示例

<script>
import axios from "axios";

export default {
  data() {
    return {};
  },
  mounted() {
    this.getMockData();
  },
  methods: {
    getMockData() {
      axios.get("/mock/goodsList").then(resp => {
        console.log(resp.data);
      });
    },
  }
};
</script>

总结

本人也是第一次使用json-server和mockjs来模拟数据,有问题再记录。

Logo

前往低代码交流专区

更多推荐