前后端分离,前端没有数据返回,就像被限制住了自由,今天介绍这款自己制作数据的方法。
"axios": "^1.1.3",
"axios-mock-adapter": "^1.21.2",
index.js 文件内容
import http from '../src/utils/http'
import MockAdapter from 'axios-mock-adapter'
const data = {
Message: '查询成功',
Code: 1,
Data: {
Id: '',
name: ''
}
}
const mock = new MockAdapter(http, { delayResponse: 2000 })
// console.log('mock', mock)
mock.onGet("/test/demo", {
params: {
name: '高峰3333'
}
}).reply(200, {
data: {
code: 200,
message: '登录成功',
data
}
})
mock.onGet("/test/login", {
params: {
name: 'admin', password: '123456'
}
}).reply(200, {
data: {
code: 200,
message: '登录成功'
}
})
.env.development
NODE_ENV=development
VUE_APP_URL =
VUE_APP_MOCK = true
.env.production
NODE_ENV=production
VUE_APP_URL =
VUE_APP_MOCK = false
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
process.env.VUE_APP_MOCK === 'true' && require('../mock/index')
new Vue({
render: h => h(App),
}).$mount('#app')
import http from '../utils/http'
// import qs from 'qs' // 请求参数序列化
export const getTest = (params) => {
console.log('getTest')
return http({
url: "/test/demo",
params
})
}
export const getLogin = (params) => {
console.log('getLogin')
return http({
url: "/test/login",
params
})
}
import { getTest } from '../api/index'
export default {
name: 'HelloWorld',
props: {
msg: String
}, data() {
return {
name: ""
}
},
mounted() {
getTest({
name: "高峰3333"
}).then(res => {
console.log(res, 'data')
this.name = res.data.result.name
})
}
}
import { getLogin } from './api/index'
export default {
name: 'App',
components: {
HelloWorld
},
mounted() {
getLogin({
name: 'admin', password: '123456'
}).then(res => {
console.log(res, '888')
})
}
}
附上axios的封装文件
import axios from 'axios'
const instance = axios.create({
baseURL: '/api',
timeout: 5000
})
instance.interceptors.request.use((config) => {
return config
})
instance.interceptors.response.use((response) => {
console.log(response, 'response')
if (response.status == 201) {
console.log(window)
}
return response.data.data
})
export default instance
参考文档:
https://www.npmjs.com/package/axios-mock-adapter
https://www.kancloud.cn/sophie_u/mockjs/534440
https://www.axios-http.cn/docs/req_config
项目源码
vue2:https://gitee.com/motain/axios-mock-adapter/tree/dev_mock
vue3:https://gitee.com/motain/v3axios-mock-adapter