想要在使用uniCloud的使用拦截请求怎么办 再次封装uniCloud.callFunction 特别说明 这里的token是我自己存储成token 如果你使用了uni-id 官方的推荐是 (‘uni_id_token’) (‘uni_id_token_expired’) 存储了uni_id_token后请求会自动携带 这里的res.result.code==0是因为我的云函数请求成功返回的code均为0 如果你的不是 就根据自己需求更改
正常情况下 我们使用uniCloud.callFunction
uniCloud.callFunction({
name: 'xxx'
})
结合uni-id后请求时需要携带token 或者需要携带一些认证参数怎么办呢 总不能一个一个的写吧 那太麻烦了
我们对他进行一次封装
根目录下新建一个目录 根据需求命名 新建index.js文件
当请求为0(根据需求调整)的时候请求成功 否则只返回相应的code(也可以返回msg等)
const req = (funName,params)=>{
const token = uni.getStorageSync('xxxx')
if(!token){
//没有token 跳转登陆
}
return new Promise((resolve)=>{
uniCloud.callFunction({
name:funName,
data:{
params
},
success:res=>{
if(res.result.code==0){
resolve(res.result)
}else{
resolve(res.result.code)
}
},
fail:()=>{
resolve(false)
}
})
})
}
module.exports = {
req
}
import Vue from 'vue'
import App from './App'
import reqFun from './reqFun/index.js'
Vue.prototype.$reqFun = reqFun
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
test() {
this.$reqFun.req(funName, params).then(res => {
})
}
const loginOrRegister = (params)=>{
return new Promise((resolve)=>{
uniCloud.callFunction({
name:'login/register',
data:{
params
},
success:res=>{
if(res.result.code==0){
resolve(res.result)
}else{
resolve(res.result.code)
}
},
fail:()=>{
resolve(false)
}
})
})
}
const req = (funName,params)=>{
const token = uni.getStorageSync('xxxx')
if(!token){
//没有token 跳转登陆
}
return new Promise((resolve)=>{
uniCloud.callFunction({
name:funName,
data:{
params
},
success:res=>{
if(res.result.code==0){
resolve(res.result)
}else{
resolve(res.result.code)
}
},
fail:()=>{
resolve(false)
}
})
})
}
const loginOrRegister = (params)=>{
return new Promise((resolve)=>{
uniCloud.callFunction({
name:'login/register',
data:{
params
},
success:res=>{
if(res.result.code==0){
resolve(res.result)
}else{
resolve(res.result.code)
}
},
fail:()=>{
resolve(false)
}
})
})
}
module.exports = {
req,
loginOrRegister
}
调用方法和通用调用一样
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有