fastmock
使用fastmock创建在线mock数据
示例: 登录验证
{
"code": "0000",
"data": {
"verifySuccess": function({_req, Mock}) {
let body = _req.body;
return body.username === 'admin' && body.password === '123456';
},
"userInfo": function({_req, Mock}) {
let body = _req.body;
if (body.username === 'admin' && body.password === '123456') {
return Mock.mock({
username: "admin",
email: "@email",
address: "@address"
});
} else {
return null;
}
},
},
"desc": "成功"
}
axios
安装axios
yarn add axios
登录时发送 post 请求
import axios from 'axios'
axios.defaults.baseURL = 'https://www.fastmock.site/mock/xxx';
export default {
setup(){
const data = reactive(
{
username: '',
password: ''
}
)
const handleLogin = () => {
axios.post('/api/user/login', {
username: data.username,
password: data.password
}).then((res) => {
if(res.data.data.verifySuccess === false) {
alert('用户名或密码不正确')
} else {
localStorage.isLogin = true
router.push({name: 'Home'})
}
}).catch(() => {
alert('失败')
})
}
}
封装axios方法
新建utils目录,新建request.ts
import axios from 'axios'
axios.defaults.baseURL = 'https://www.fastmock.site/mock/xxx/jd'
axios.defaults.headers.post['Content-Type'] = 'application/application/json'
const post = async (url: string, data: any = {}) => {
const response = await axios.post(url, data)
return response.data
}
export {
post,
}
使用
import {post} from '@/utils/request'
const handleLogin = async () => {
try {
const result = await post('/user/login', {
username: data.username,
password: data.password
})
if(result.data.verifySuccess === true) {
localStorage.isLogin = true
router.push({name: 'Home'})
} else {
alert('用户名或密码错误')
}
} catch(e) {
console.log(e)
alert('请求失败')
}
}
上面使用 async/await 做的封装,也可以使用 promise 封装
import axios from 'axios'
export const post = (url, data={}) => {
return new Promise((resolve, reject) => {
axios.post(url, data, {
baseURL: 'xxx',
headers: {
'Content-Type': 'application/json'
}
}
}).then(response => {
resolve(response.data)
}, err => {
reject(err)
})
}
添加get方法
import axios from 'axios'
axios.defaults.baseURL = 'https://www.fastmock.site/mock/xxx/jd'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const post = async (url: string, data: any = {}) => {
const response = await axios.post(url, data)
return response.data
}
const get = async (url: string) => {
const response = await axios.get(url)
return response.data
}
export { post, get }
instance
另一种方法是创建axios实例,并传入 config 信息,再使用实例
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://www.fastmock.site/mock/xxx/jd',
})
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const post = async (url: string, data: any = {}) => {
const response = await instance.post(url, data)
return response.data
}
const get = async (url: string) => {
const response = await instance.get(url)
return response.data
}
export { post, get }