1、api的调用也是我们日常工作的重要组成部分,下面我就来看一下uniapp中api是如何调用的
首先在utils(没有就创建一个)中创建一个request.js:
// 添加token,拦截错误,添加请求头
import {baseURL,timeout} from '../config/index'
const request = function(option){
// 获取用户传入的url
var url = option.url;
// 定义一个正则表达式 必须http 或者https开头
var reg = /^https?/i;
// 如果不是http开头
if(!reg.test(url)){
// 地址加baseURl
url=baseURL+url;
}
// 添加提请求头
var header = option.header||{}
// 添加token
header.token = uni.getStorageSync('token');
// header.Cookie = 'passToken='+uni.getStorageSync('token');
header.source=1;
header.channel="h5";
// 加载提示
var loading = option.loading;
// 如果有loading就显示loading
if(loading){
uni.showLoading(loading)
}
// 返回一个promise
return new Promise((resolve,reject)=>{
// 发起一个request请求
uni.request({
url, //请求url
method:option.method||"GET", //请求方法
header, //请求头
timeout,
data:option.data||option.params, //请求数据
success(res){
// 成功返回结果
if(res.statusCode===200){
resolve(res.data)
// 如果是101 没有权限
// if(res.data.code==101){
// uni.showToast({
// title: res.data.msg,
// icon:'none'
// })
// uni.redirectTo({
// url: '/pages/login/login',
// })
// }
if(res.data.code!=200&&res.data.code!=0){
uni.showToast({
icon:'none',
title:res.data.msg||'请求错误'
})
}
}
},
fail(err){
// 失败返回失败结果
uni.showToast({
title: '请求失败',
icon:'error'
})
console.error(err);
reject(err)
},
complete(){
// 完成 关闭loading
if(loading){
uni.hideLoading()
}
}
})
})
}
// 定义get简洁方法
request.get=function(url,config){
return request({
url,
method:"GET",
...config
})
}
// 定义post简洁方法
request.post=function(url,data,config){
return request({
url,
method:"POST",
...config,
data
})
}
// 导入请求
export default request;
完成对各种请求以及一下返回状态码结果的封装弹框等等,在config/index中定义一些基础的信息:
export const baseURL = "https://127.0.0.1"
export const timeout = 5000
2、封装api调用方法,在api文件夹下的index.js:
import request from '@/utils/request.js'
// 获取走马灯
export function getSwiper(){
return request.get("/mall/home/new_product",{loading:{
title:'加载中',
icon:'loading'
}})
}
// 发送验证码
export function sendCode(data){
return request.post("https://127.0.0.1/v1/identity/sendCode",data)
}
// 登录
// export function smsLogin(data){
// // 返回的一个promise
// return new Promise((reslove,reject)=>{
// uni.request({
// url:"/v1/sso/smsLogin",
// method:"POST",
// data,
// header:{
// "X-XSRF-TOKEN": "eyJpdiI6Imx6amoyVUpXNWZUQlhIcnZadG1aRGc9PSIsInZhbHVlIjoiNllqU3BzSXZrckY0R2NZRk5WMEhKcnd0eWZOQlVvXC9QUnF6WDRwK3YxRmF4Qm1uTFJ3TytGYUtzayt3Z2Nud3dYY1hDa1NQUmVEUk1iZUxoUHdXZXFRPT0iLCJtYWMiOiI0M2RiYWVkY2U2N2U0MDJhY2MzMGU5YjNiNDYwYzZlN2FlOWEwOTllY2FlZTVmNjAwOTRmYWU5MGMxZDQyNTgwIn0="
// },
// success(res){
// // 返回的是整体数据信息,header和data
// reslove(res)
// },
// fail(err){
// reject(err);
// }
// })
// })
// // return request.post("https://127.0.0.1/v1/sso/smsLogin",data)
// }
export function smsLogin(data){
return request.post("https://127.0.0.1/v1/sso/smsLogin",data);
}
// 获取用户信息
export function getUserInfo(){
return request.get("https://127.0.0.1/open/oauth2/login/checkLogin",{
header:{
source: 1,
token: uni.getStorageSync("token"),
channel: "h5",
}
})
}
export function getOpenid(params){
return request.get("https://127.0.0.1//study_miniprog_openid",{params})
}
export function getPayParams(params){
return request.get("https://127.0.0.1//study_miniprog_pay",{params})
}
export function getOrderInfo(data){
return request.post('https://127.0.0.1/http/pay',data)
}
export function getId(data){
return request.post("https://127.0.0.1//http/user-center",data);
}
// 定义详情的接口
export function getBaseInfo(params){
return request.get("https://127.0.0.1/mall/sku/detail/basic_info",{params})
}
// 加入购物车
export function addCart(data){
return request.post("https://127.0.0.1//api/addcart",data)
}
// 流程确认(用户的收货地址,优惠券。。。)
export function flowCheck(){
return request.get("https://127.0.0.1//flow-check")
}
最后就是调用:
<template>
<view>
<input v-model="phoneInfo.account" placeholder="手机号"/>
<input placeholder="验证码" v-model="loginInfo.code"/> <button size="mini" @click="getCode">获取验证码</button>
<button @click="login" >登录</button>
</view>
</template>
<script setup>
// 导入仓库
import {useAuthStore} from '@/stores/useAuthStore.js'
import {sendCode, getUserInfo,smsLogin} from '@/api/index.js'
import {ref} from 'vue'
// 使用仓库
const store = useAuthStore();
// 发送验证码需要的信息
const phoneInfo = ref({
"mobileArea":"+86",
"account":"",
"type":2
})
// 登录需要的信息
const loginInfo = ref({"mobileArea":"+86","mobile":"","code":"","sourceCode":601,"callback":"https://m.xgimi.com/pages/user/user"})
function getCode(){
sendCode(phoneInfo.value)
.then(res=>{
if(res.code===200){
uni.showToast({
title:"验证码发送到您的手机",
icon:'none'
})
}
})
}
// 执行登录
function login(){
// 更新mobile的值
loginInfo.value.mobile = phoneInfo.value.account;
// 传参一定传value值
smsLogin(loginInfo.value)
.then(res=>{
if(res.code===200){
// 存储本地数的token
uni.setStorageSync("token",res.data.passToken)
// 仓库去获取用户信息
store.getUser();
// 跳转到用户页面
uni.switchTab({
url:"/pages/user/user"
})
}
})
}
</script>
<style>
</style>
2023-09-19 start:
https://uniapp.dcloud.net.cn/api/system/info.html
end
2023-10-09 start:
uniapp的文件上传接口注意查看官方文档:
uni.uploadFile(OBJECT) | uni-app官网 (dcloud.net.cn)
uni.uploadFile(options) @uploadfile | uni-app官网 (dcloud.net.cn)
不能直接使用uni.request来进行文件上传,需要使用uni.unupload进行
例如我们可以在request.js直接定义:
// 定义文件上传简洁方法
request.upload=function(url,data,files){
// 定义一个正则表达式 必须http 或者https开头
var reg = /^https?/i;
// 如果不是http开头
if(!reg.test(url)){
// 地址加baseURl
url=baseURL+url;
}
var header = {}
header.Authorization = 'Bearer '+ uni.getStorageSync('access_token');
return new Promise((resolve,reject)=>{
uni.uploadFile({
url,
files,
formData: data,
header, //请求头
timeout,
success: (res) => {
// 成功返回结果
if(res.statusCode===200){
resolve(res.data)
if(res.data.code!=200&&res.data.code!=0){
// uni.showToast({
// icon:'none',
// title:res.data.msg||'请求错误'
// })
// console.log(res.data.msg)
}
} else if (res.statusCode===401) {
resolve(res.data)
uni.showToast({
title: res.data,
icon:'none'
})
uni.redirectTo({
url: '/pages/login/login',
})
} else {
resolve(res.data)
}
},
fail(err){
// 失败返回失败结果
uni.showToast({
title: '请求失败',
icon:'error'
})
console.error(err);
reject(err)
},
complete(){
}
});
})
}
调用:(data参数插入对象的形式,filesData传入为(路径)数组的的形式)
// {
// para
// }
export function upload(data,filesData){
let files = []
for (let i = 0 ; i < filesData.length ; i++) {
let file = {
name:"images",
uri:filesData[i]
}
files.push(file)
}
return request.upload("/upload",data,files)
}
end