在前后端分离的项目中,后端接口可能与我们前端是一起开发的。此时在没有后端接口的前提下,我们就需要自己模拟后台接口,发起ajax请求。
npm install axios
npm i mockjs -S
安装完axios与mockjs后,就是配置mockjs了。目录结构:
./mock/index.js
const Mock = require('mockjs');
const mockFiles = require.context('./modules', false, /\.js$/); // 适用于Vue2
// const baseUrl = "https://localhost:8081"
let mocks = [];
mockFiles.keys().forEach(key => {
mocks.push(...mockFiles(key))
})
mocks.forEach(item => {
Mock.mock(item.url, item.type, item.response)
})
/*
// Vue3弃用了require.context,所以我们使用:
const mockArrNew = import.meta.globEager('./modules/*.js')
Object.values(mockArrNew).map(el=>el.default[0]).forEach(key => {
let el = mockArrNew(key).default[0]
mocks.push(el)
})
*/
./mock/modules/user.js
const userList = {
url: /\/user\/list/, // 正则匹配
type: "get",
response: () => {
return {
code: 200,
data: [
{
"id": 1,
"username": "zhoujielun",
"password": "123456"
},
{
"id": 2,
"username": "guojingming",
"password": "666666"
},
]
}
}
}
const userList1 = {
url: "/user/list1", // 字符串写死,这种写法会无法匹配带参数的get请求
type: "get",
response: () => {
return {
code: 200,
data: [
{
"id": 1,
"username": "zhoujielun",
"password": "123456"
},
{
"id": 2,
"username": "guojingming",
"password": "666666"
},
]
}
}
}
module.exports = [
userList,
userList1,
]
然后在main.js中引入:
import "@/mock/index.js"
// 或者
require("./mock/index.js")
App.vue中使用
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
import axios from "axios"
export default {
name: 'App',
data() {
return {
} },
mounted() {
axios.get("https://localhost:8081/user/list").then(res => {
console.log("res", res) })
}
}
</script>
<style lang="scss" scoped>
</style>
最后在控制台输入:
npm run dev
以下是控制台打印的内容:
注意,mockjs是模拟后台发起ajax请求,在控制台的network是看不见请求的。
补充说明 ——2021-12-10
用axios发起请求时,发现post请求时,这种写法会报错,mockjs监听不到post请求
// 会报错
axios({
type: "POST",
url: url,
data: data,
headers: headers
}).then(res => {
resolve(res) })
.catch(err => {
reject(err) })
mock.js里的定义: // 获取用户信息
function getFullname(config) {
return {
code: 0,
result: {
fullname: "kingmed" }
}
}
const getFullnameObj = {
url: /\/init\/getFullname/,
type: "post",
response: getFullname
}
module.exports = [
getFullnameObj
]
报错的信息:
然后我将post请求的方式改为
axios.post(url, data, headers)
.then(res => {
console.log(res)
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
就不会报错了,奇怪。
特此记录,以供参考与交流,若有错误,请大家指出,我们一起学习,谢谢!