1.在项目根目录(pages同级目录)新建utils文件夹 , 在utils文件夹内新建request.js文件内容如下:
//1.md5是从数据交互安全考虑进行加密 , 如不需要可不用使用
import md5 from './md5.js' //文件可从网上下载 放在utils文件夹下
const baseUrl = 'https://formal.com/' //正式环境地址 需要更换成自己项目请求正式环境地址
//const baseUrl = 'https://test.com/' //测试环境地址 需要更换成自己项目请求测试环境地址
let timestamp = Math.round(new Date().getTime() / 1000).toString() //当前时间戳
let secret = 'c8bef9c31576a5e7c48dcb27a558cb8c'
let sign = md5(secret + timestamp) //MD5加密字符串
let token = uni.getStorageSync('token') //token
//封装请求Promise模式请求
export default function request(url, params, method = 'GET') {
return new Promise((reslove, reject) => {
uni.request({
url: baseUrl + url,
method: method || 'GET',
header: {//可根据需要自行添加或删除参数
'sign': sign,
'timestamp': timestamp,
'Authorization':token
},
data: params || {},
success: (res) => {
if (res.data.code == 0) {
reslove(res.data, res);
} else if (res.data.code == 10003) {//统一处理状态码 状态码根据自己项目设置即可
uni.navigateTo({
url: "/pages/login/login"
});
} else if (res.data.code !== 0 && res.data.code !== 10003) {//统一处理状态码 状态码根据自己项目设置即可
uni.showToast({
title: res.data.msg || '系统错误',
icon: 'none',
duration: 2000
});
reject(res.data.msg || '系统错误');
}
},
fail: (msg) => {
reject('请求失败');
}
})
});
}
2.在main.js文件内引入封装好的request文件
import App from './App'
import Vue from 'vue'
// #ifndef VUE3
import request from'utils/request.js' //引入请求文件
Vue.config.productionTip = false
Vue.prototype.$api = request //把文件注入到Vue原型中
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
// #endif
3.完成以上2步后即可在全局使用, 使用中注意参数顺序不要传错(url, params, method = 'GET') , 后2个参数可不传
//在页面中使用
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
this.get()
},
methods: {
get(){
this.$api('api/user/info').then(res=>{ //
console.log(res)
})
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
网友评论