How does axios in vue3 match mockjs simulation interface to automatically import modules, and the data of each request interface is inconsistent

Table of contents

1 axios-related

1.1 Introducing axios

1.2 Add request interception

1.3 Use axios to call the interface

1.4 Test whether axios is successful

2 mockjs related

2.1 First install mockjs

2.2 According to your own needs, create a folder to store the code of the analog interface

2.3 Create a file test.js in _modules and write a test code

2.4 Introduce module code under mock/index.js

2.5 Introduce mock in main.js

2.6 Test whether the mock is successful


Source address icon-default.png?t=M4ADhttps://github.com/liuxin00020/vue3-elementplus-axios-mock-echarts ​​​​​​​​1 axios related

1.1 Introducing axios

npm install axios --save

1.2 Add request interception

Create an axios.js file in a suitable location (the blogger is in utils/axios.js), the blogger is lazy, and the interception is very simple

/*
 * @Author: liuxin
 * @Date: 2022-04-19 15:42:34
 * @LastEditors: liuxin
 * @LastEditTime: 2022-06-10 14:13:53
 * @Description: 请求拦截
 */
import axios from "axios";
import { ElMessage } from 'element-plus'
import "element-plus/es/components/message/style/css"

// 这里打包后,可以修改根目录下的config.js进行修改
axios.defaults.baseURL = Window.apiConfig[process.env.NODE_ENV].baseUrl

// 请求拦截器,内部根据返回值,重新组装,统一管理。
axios.interceptors.response.use(res => {
    const { data } = res;
    if (typeof data !== 'object') {
        ElMessage.error('服务器异常,请联系管理员')
        return Promise.reject(res);
    }
    if (data.code != 200) {
        if (res.data.message)
            ElMessage.error(res.data.message)
        return Promise.reject(res.data);
    }

    return data
}, (err) => {
    ElMessage.error({
        showClose: true,
        message: '服务器异常,请联系管理员',
        type: 'error',
    })
    return Promise.reject(err)
})

export default axios;

1.3 Use axios to call the interface

Try to see if the interception takes effect under the appropriate code. The blogger code is in apis/mockTest.js

/*
 * @Author: liuxin
 * @Date: 2022-06-10 13:59:41
 * @LastEditors: liuxin
 * @LastEditTime: 2022-06-10 16:05:46
 * @Description: 测试mockjs
 */
import axios from "@/utils/axios.js"

/**
 * @description:  或者列表
 * @Author: liuxin
 */
export const getUseList = (param) => {
    return axios.post('/getUseList', param)
}

1.4 Test whether axios is successful

At this time, if there is no backend and an error 404 is reported, it means that axios has succeeded. If it succeeds, look down. If it fails, find the reason by yourself.

    /**
     * @description: 获取数据
     * @Author: liuxin
     */
    const getList = () => {
      state.loading = true;
      getUseList({ userName: state.userName })
        .then((res) => {
          state.loading = false;
          state.tableData = res.data;
        })
        .catch(() => {
          state.loading = false;
          state.tableData = [];
        });
    };

2 mockjs related

2.1 First install mockjs

I use it in the development environment, so it is installed in the development dependency

npm install mockjs --save-dev

2.2 According to your own needs, create a folder to store the code of the analog interface

index.js is the entry file, and _modules is the analog interface code of the relevant modules, which is automatically introduced here, that is to say, you only need to write the corresponding code in the _modules creation file in the future

2.3  Create a file test.js in _modules and write a test code

/*
 * @Author: liuxin
 * @Date: 2022-06-09 17:21:17
 * @LastEditors: liuxin
 * @LastEditTime: 2022-06-10 16:44:38
 * @Description: 测试mock接口数据
 */
/**
 * @description:  测试
 * @Author: liuxin
 */
import Mock from "mockjs";
export default [
    {
        url: "/api/getUseList", // 这个url就是后端给的url,需要与apis里面调用的url保持一致
        type: "post",
        getData: (param) => {
            return Mock.mock({
                code: 200,
                message: "success",
                param: param,
                "data|1-20": [{
                    'date': "@date",
                    'name': param.userName + "@string(5)",
                    'age': "@integer(1, 100)",
                    'sex|1': ['男', '女', '未知'],
                }]
            })
        }
    },
];

2.4 Introduce module code under mock/index.js

/*
 * @Author: liuxin
 * @Date: 2022-06-09 17:21:03
 * @LastEditors: liuxin
 * @LastEditTime: 2022-06-10 16:50:42
 * @Description: 模拟接口自动引入入口页
 */
import Mock from "mockjs";

// 自动引入模块
const modulesFiles = require.context('./_modules', true, /\.js$/);

const mocks = modulesFiles.keys().reduce((modues, item) => {
    return [...modues, ...modulesFiles(item).default];
}, [])

// 设置拦截ajax请求的响应时间
Mock.setup({
    timeout: "200-1000"
});
// 遍历mock配置项
mocks.forEach(item => {
    Mock.mock(item.url, options => {
        const { type, body } = options;
        if (item.type !== type.toLowerCase()) {
            return { code: 500, msg: `该接口不支持${type}方式` };
        } else {
            return item.getData(JSON.parse(body)); // 这样每次调用接口,返回的数据才不一样
        }
    });
});

2.5 Introduce mock in main.js

// 引入mocks,测试接口
if (process.env.NODE_ENV === "development") {
    require("./mock");
}

2.6 Test whether the mock is successful

Before calling the interface, an error 404 was reported. Now refresh and look at the result, and the print out has been successful.

Guess you like

Origin blog.csdn.net/liuxin00020/article/details/125082135