问题还原
- 项目中引入mockjs配置好测试,请求报404错误
项目框架
- vue3.2+ts+webpack+axios+mockjs
- node: 14
- vuecli:4.5
操作步骤
1.新建一个vue3项目
vue create 项目名
2.安装axios
npm i axios
3.安装mockjs
npm i --save-dev mockjs
npm i --save-dev @types/mockjs
4.mock接口
mock列表数据
// src/mock/index.ts import Mock from "mockjs"; const { item } = Mock.mock({ "item|6": [ { id: "@id", label: "@csentence(1,2)", value: "@sentence(1)", "status|1": ["published", "draft", "deleted"], time: "@datetime", pageNum: "@integer(0,100)", "active|1": [true, false], }, ], });
- 官网文档有详细的语法规则
5.拦截axios请求
// src/mock/index.ts // 获取mock的响应数据 const getResponse = ( url: string, type: string, data: {}[], condition: boolean ) => { return { url, type: type || "get", response: (config: any) => { console.log(config, type); return condition ? { code: 200, success: true, message: "请求数据成功", content: { total: data.length, data, }, } : { code: 500, success: false, message: "请求数据失败", }; }, }; }; const mocks = [ getResponse("/api/list", "get", item, true), getResponse("/api/productList", "post", item, true), ]; export const mockXHR = () => { for (const i of mocks) { Mock.mock(new RegExp(i.url), i.type || "get", i.response); } };
6.全局调用
- mian.ts内调用
7.测试请求
封装请求api
// src/api/index.ts import axios from "axios"; export const getList = () => { return axios("/api/list"); }; export const getProductList = (data:object) => { return axios({ method:'post', url:"/api/list", data }); };
页面调用接口测试
// src/views/test.vue <script setup lang="ts"> import { getList, getProductList } from "../api/index"; const test = async () => { let res1 = await getList(); let res2 = await getProductList({ id: 0 }); console.log("mock-get", res1); console.log("mock-post", res2); }; </script> <template> <div id="Container"> <button @click="test">mock数据</button> </div> </template> <style lang="scss" scoped> #Container { height: 50vh; border: 10px solid #000; display: flex; justify-content: center; align-items: center; } </style>
总结:
- mockjs根据匹配到的url字段拦截axios请求,打开控制台network不会发网络请求,一旦匹配到相应的返回自己mock的响应数据;
- 之所以控制台报请求404的错误,是因为没有拦截到请求,在本地开发还没有后台的时候依然请求这个地址自然会报404;
- 务必检查拦截url字段 以及 请求方式(本人栽坑处)非常重要
相关链接
- mockjs官网: http://mockjs.com/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。