封装请求接口(不带loading)
在pages的同级 创建一个api文件 里面写2个文件
request.js index.js
request.js
// import store from '@/store/store.js'
//apiUrl为域名 url请求接口
let apiUrl="https://cnodejs.org/api/v1"
async function get(url,data){
let res = await uni.request({
url:apiUrl+url,
data:data,
method:'GET',
header:{'Authorization':uni.getStorageSync('token'),
'content-type': 'application/json'},
})
return res[1].data;
}
async function post(url,data){
let res = await uni.request({
url:store.state.apiUrl+url,
data:data,
method:'POST',
header:{'Authorization':uni.getStorageSync('token'),
'content-type': 'application/json'},
})
return res[1].data;
}
async function del(url,data){
let res = await uni.request({
url:store.state.apiUrl+url,
data:data,
method:'DELETE',
header:{'Authorization':uni.getStorageSync('token'),
'content-type': 'application/json'},
})
return res[1].data;
}
async function put(url,data){
let res = await uni.request({
url:store.state.apiUrl+url,
data:data,
method:'PUT',
header:{'Authorization':uni.getStorageSync('token'),
'content-type': 'application/json'},
})
return res[1].data;
}
export default {
get,
post,
del,
put
}
index.js
//引入request.js
import api from './request.js'
// 首页
async function swiper(data){
return await api.get('/topics',data);
}
//导出
export default {
swiper
}
在main.js 引入一下
import index from '@/api/index.js'
Vue.prototype.$index = index
然后在页面使用时
<template>
</template>
<script>
export default {
data() {
return {}
},
created() {
this.getSwiper()
},
methods: {
getSwiper() {
uni.showLoading({
title: "加载中",
mask: true,
});
//需要传给后台的数据
let data = {
type: 0
}
//请求接口
this.$index.swiper(data).then(res => {
if (res.success == true) {
uni.hideLoading();
}
})
}
}
}
</script>
<style>
</style>
然后这边就请求成功数据了 这边以cnode接口为列 具体看你们公司的接口数据
这个不好的是每个请求都要写请求加载一次
封装请求接口(带loading)
在utils文件 新建一个request.js文件封装uni.request
const BASE_URL = 'https://cnodejs.org/api/v1' //开发环境与生还环境的基地址
export const request = (http) => {
uni.showLoading({
title: '加载中',
mask: true,
});
const {
url,
data,
method,
header={
'token': '',//封装token的信息
'content-type':'application/json || charset=UTF-8'//请求头的状态
}
} = http
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + url,
method,
data,
header:header,
success: (res) => { //请求成功
if (res) { //这里后台返回一个自定义状态码,可根据实际开发情况调整
uni.hideLoading();
resolve(res)
} else {
uni.showToast({
title: '请求数据失败!'
})
}
},
fail: (err) => { //请求失败
uni.showToast({
title: '请求数据失败!'
})
reject(err)
}
})
})
}
在api文件新建一个index.js封装对应的api
import {request} from '../utils/request'
export const getData = (data) => request({
url: '/topics',
method: 'get',
data
})
页面使用
!<template>
<view>1212121</view>
</template>
<script>
import *as request from '../../api/api'
export default {
data() {
return {};
},
onShow() {
this.list();
},
methods: {
list() {
let params = {
page: 1,
limit: 10,
};
request.getData(params).then((res) => {
console.log(res);
});
},
},
};
</script>
<style>
</style>
上传图片封装
千里之行
始于足下