1:创建 request.js 文件
// 测试地址
// export const BASE_URL = 'http://43.143.229.55/dev-api'
// 本地地址 通过传入的 BASE_URLS 来判断使用哪一个API
export const BASE_URL = 'http://192.168.0.0:8080'
export const BASE_URLS = 'http://192.168.0.1:8081'
export const request = (options) => {
// 同时发送异步代码的次数,防止一次点击中有多次请求,用于处理
let ajaxTimes = 0;
let loading = true;
// 当前请求不是登录时请求,在header中加上后端返回的token
// let header = uni.getStorageSync('token') ? {
// Authorization: 'Bearer ' + uni.getStorageSync('token')
// } : '';
ajaxTimes++;
if(options.Headers&&options.Headers.showloading===false) {
loading = false
}
if(loading) {
uni.showLoading({
title: "加载中",
mask: true,
});
}
return new Promise((resolve, reject) => {
// let token = uni.getStorageSync('token')
uni.request({
url: (options.BASE_URLS?BASE_URLS:BASE_URL) + options.url,
method: options.method || 'GET',
// header,
data: options.data || {},
success: (res) => {
// 202表示没有token
// if (res.data.code == 202) { // 如果请求失败,则给一个提示 并返回登录页
// uni.showToast({
// title: '请重新登录',
// icon: 'none'
// })
// return uni.reLaunch({
// url: '/pages/login/login'
// });
// }
// 用箭头函数,res是返回来的数据
if (res.data.code !== 200) {
uni.showToast({ // 如果请求失败,则给一个提示
title: res.data.msg,
icon: 'none'
})
reject(res)
return
}
// 200 返回数据
resolve(res.data.data)
},
fail: (err) => { // err 是返回来的错误信息
uni.showToast({ // 给一个消息提示
title: err.errMsg||'请求接口失败!',
icon:"none"
})
reject(err) // 调用reject方法把错误消息返回出去
},
// 完成之后关闭加载效果
complete: () => {
ajaxTimes--;
if (ajaxTimes === 0) {
// 关闭正在等待的图标
uni.hideLoading();
}
}
})
})
}
2: 创建 index.js 引入第一步创建的 request.js文件
import {request} from '@/ulits/request'
// 查询用户协议
export function getUserInfo(query) {
return request({
url: '/getUser/info',
method: 'get',
data: query
})
}
3:在你需要用到的的页面 引入第二步创建的 jindex.js文件 就可以访问后端的接口开始联调了
<template>
<!-- 用户协议 -->
<view class="box">
<view v-html="data">
</view>
</view>
</template>
<script>
import {getUserInfo} from "@/api/index.js"
export default {
data() {
return {
data:''
}
},
onLoad() {
getUserInfo({type:1}).then(res=>{
this.data=res
console.log(res,'----');
})
},
methods: {
}
}
</script>
<style>
.box{
padding: 30rpx;
}
</style>