先建立一个文件夹 common 在根目录下
建立一个ajax.js文件 文件代码
我这里把token存在vuex里了 所以引用了vuex 不需要的话可以删掉
import Vue from 'vue'
import {
store
} from '../../store/index.js';
function ToastError(d) {
uni.showToast({
icon: 'none',
title: d.msg || d.message || '未知错误'
})
}
export default function http(url, data, method = 'GET', showError = true) {
const state = Vue.prototype.$store.state;
return new Promise((resolve, reject) => {
uni.request({
url: `${Vue.prototype.$baseURL}${url}`,
method,
data: data,
header: {
'X-Csrf-Token': state.token
},
success(res) {
console.log(res)
if (正确的code) {
resolve(resData.data);
// http status 200 && data.code 444 为登录失效 或 未登录
}else {
uni.hideLoading()
showError && ToastError(res.data);
reject(res);
}
},
fail(e = {}) {
console.log(e);
if (e.errMsg && e.errMsg.startsWith('request:fail ')) {
e.msg = '网络错误'
}
showError && ToastError(e);
reject(e);
}
});
});
}
建立一个api.js文件 引入刚才的ajax.js
这里面有get和post请求的实例
import ajax from './ajax.js';
export function test(phone) {
return http(`/test/${phone}`);
}
// 登录接口
export function test(body) {
return http('/test', body, 'POST');
}
在main.js挂载一下请求地址
Vue.prototype.$baseURL = "https://12345";
在页面的时候先引入api.js 里面需要请求的接口 就可以在页面里使用了
import {
test
} from '../../public/lib/api.js'
test(body).then((res) => {
console.log(res)
}).catch((res)=>{
console.log(res)
});