当前位置: 首页 > Web前端 > HTML5

uni-app的封装需要openid或者token请求

时间:2023-04-05 14:10:30 HTML5

1.用户首次登录时,将返回的openid存入缓存,success:function(){uni.login({success:function(res){uni.request({url:that.apiUrl+'small/index/GetOpenid?code='+res.code,success:(res)=>{console.log(res)if(res.data.openid){//将openid保存在缓存中uni.setStorageSync('openid',res.data.openid)userinfoDetails.openid=res.data.openid}}})}})}});},2。新建一个config.js封装请求constapp={apiUrl:'https://aaa.bbb.com/',//请求的域名openidRequest(obj){try{constopenid=uni.getStorageSync('openid');if(openid){if(obj.data){obj.data["openid"]=openid;}else{obj.data={"openid":openid};}obj.url=this.apiUrl+obj.url;uni.request(obj)}else{console.log("无法获取openid")}}catch(e){console.log(e)console.log("无法获取openid")}},}exportdefault应用程序;3、在页面调用中,需要使用openid作为参数的requestimportappfrom'../../common/config.js'exportdefault{onLoad(){this.getTeamlist()},methods:{getTeamlist(){varthat=thisapp.openidRequest({url:'test/abc',//如果请求的URL是:https://aaa.bbb.com/test/abc,那么这里的url只需要写'test/abc'方法:'POST',标题:{'content-type':'apapplication/x-www-form-urlencoded',},success:(res)=>{this.teamlist=res.data.teamlist}})}},}下面是token,把openid换成userTokenconfig即可。jsconstapp={apiUrl:'http://216:18080/webcase/',//请求地址baseRequest(obj){try{constuserToken=uni.getStorageSync('userToken');if(userToken){if(obj.header){obj.header["token"]=userToken;}else{obj.header={"token":userToken};}obj.url=this.apiUrl+obj.url;uni.request(obj)}else{console.log("无法获取userToken")}}catch(e){console.log(e)console.log("无法获取userToken")}},}导出默认应用;需要使用从“@/api/apiConfig”获取的页面导入应用程序UserStatus(){app.baseRequest({url:'getUserStatus',method:'POST',success:(res)=>{//将用户状态存储在缓存中try{uni.setStorageSync('userStatus',res.data.data.type)uni.setStorageSync('userAgentInfo',res.data.data)}catch(e){//TODO处理异常}if(res.data.data.type==2){this.getLawInfo()}else{this.yhju=false}}})}