uniapp把请求接口封装起来
文章描述:
uniapp封装request请求接口
1、在根目录新建common目录,然后在目录下面新建config.js、request.js、api.js
config.js代码
export const BASE_URL = 'https://xxx.xxx.com/api'
request.js代码
import {BASE_URL} from '@/common/config'
const defauls = {
method: "GET",
loading: true
}
console.log(BASE_URL)
// 全局请求封装
export default (path, data = {}, method = 'GET') => {
// console.log('%c请求拦截:', ' background:orange', data);
const token = uni.getStorageSync("token") ? `${uni.getStorageSync("token")}` : "";
uni.showLoading({
title: "加载中",
mask: true
});
return new Promise((resolve, reject) => {
uni.request({
header:{token},
url: BASE_URL + path,
method: method,
data,
success(response) {
// console.log('%c响应拦截:', ' background:green', response);
if (response.data.code === 3001) {
// logout()
}
if (response.data.code !== 20) {
uni.showToast({
icon: "none",
duration: 4000,
title: response.data.msg
});
}
resolve(response.data);
},
fail(err) {
uni.showToast({
icon: "none",
title: '服务响应失败'
});
console.error(err);
reject(err);
},
complete() {
uni.hideLoading();
}
});
});
};
api.js
import request from "@/common/request.js"
export default {
// 密码登录
passwordLogin(params) {
return request("/Staff.Login/login", params, 'POST')
// return request("/Staff.Login/login", params)
},
// 短信登录
noteLogin(params) {
return request("/platform/metadata/login", params)
},
// 获取验证码:用于短信登陆、密码找回、用户注销
getAuthCode(params) {
return request("/platform/metadata/sms", params)
},
// 获取注册账号验证码
getRegistAuthCode(params) {
return request("/platform/metadata/sms1", params)
},
// 登录者信息
getMyInfo(params) {
return request("/platform/metadata/bindinfo", params)
},
}
页面调用
import api from '../../common/api.js'
export default {
data() {
return {
title: 'Hello',
loginData:{
userName:'xxx',
passWord:'xxx',
}
}
},
onLoad() {
uni.setStorageSync('token','ABCDEFG')
this.login()
},
methods: {
login(){
let params = {
staff_code:'403063',
password:'123456'
}
api.passwordLogin(params).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
}
全局调用
main.js
//导入封装的请求对象
import api from './common/api.js'
//将请求对象设置为全局属性
Vue.prototype.$api = api
使用方法
login(){
let params = {
staff_code:'403063',
password:'123456'
}
this.$api.passwordLogin(params).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
},
发布时间:2023/12/09
发表评论