第一次封装
先建目录utils/request.js,在里面放进以下代码
基地址要改成后端地址
export const baseURL = '基地址'
export const request = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: baseURL + options.url, //接口地址:前缀+方法中传入的地址
method: options.method || 'GET', //请求方法:传入的方法或者默认是“GET”
data: options.data || {}, //传递参数:传入的参数或者默认传递空集合
header: {
'token': uni.getStorageSync("token") || "" //自定义请求头信息
},
success: (res) => {
console.log(res, uni.getStorageSync('token'));
//返回的数据(不固定,看后端接口,这里是做了一个判断,如果不为true,用uni.showToast方法提示获取数据失败)
if (res.data.code == 1) {
resolve(res.data.data)
} else {
if(res.data.code== 401){
uni.navigateTo({
url:'/login/login'
})
uni.clearStorageSync()
}
reject(res.data.msg)
}
// 如果不满足上述判断就输出数据
},
// 这里的接口请求,如果出现问题就输出接口请求失败
fail: (err) => {
console.log(err)
reject(err)
}
})
})
}
第二次封装
先建目录api/index.js,在里面放进以下代码
import {
request
} from '@/utils/request.js'
// 获取论坛类型 /api/forum/ftype/index
export const getForumType = (page, rows) => request({url: 'forum/ftype/index',method: 'post',data: {page,rows}})
每次接口都需要定义一下 ,然后每次使用时的时候按需引入一下
页面使用的时候需要,这个async需要在onLoad里使用,才有快捷键,快捷键的设置方法如下图。
onLoad() {
async getForumType(){
import { getForumType } from '@/api/' //这一行需要放在script下,最上面一行
try {
const res = await getForumType()
console.log('getForumType', res)
// 保存数据
} catch (err) {
uni.showToast({ title:err,icon:'none' })
console.log('getForumType', err)
}
},
},