当前位置:   article > 正文

uniapp 封装请求接口 (带token)_uniapp封装请求携带token

uniapp封装请求携带token

uniapp 封装请求接口 (带token)

1.在创建好的uniapp项目中新建文件夹util,再新建config.js文件配置baseUrl

export default {
	//接口请求域名配置
	baseUrl : 'https://xxxx.com'
}
 
  • 1
  • 2
  • 3
  • 4
  • 5

2.新建request.js文件 ,封装请求

import config from "./config.js"

const headers = {}
const url = {}
url.request = async (url, params = {}, method, needDataSource = 0, needToken = false, needLoading = true) => {
	if (needLoading == true) {
		uni.showLoading({
			title: '加载中',
		})
	}
	
	if (needToken) {
	    //登录时存储token uni.setStorageSync('token',data.accessToken)
		const Authorization = uni.getStorageSync('token')
		//请求头拼接
		headers['Authorization'] = 'Bearer '+Authorization
	}else {
		delete headers['Authorization']; 
	}
	switch (needDataSource) {
		case 0:
			headers['x-datasource'] = 'shtraining'
			break;
		case 1:
			headers['x-datasource'] = 'shtraining-lab'
			break;
	}
	let full_url = config.baseUrl + url;
	return await uni.request({
		url: full_url,
		header: headers,
		data: params||{},
		method: method,
	}).then(res => {
		uni.hideLoading()
		if (!res) {
			return 0;
		}
		console.log(res.data);
		return res.data;

	}).catch(parmas => {
		uni.hideLoading()
		switch (parmas.code) {
			case 401:
				uni.clearStorageSync()
				break
			default:
				uni.showToast({
					title: parmas.message,
					icon: 'none'
				})
				return Promise.reject()
				break
		}
	})
}
//导出
export default url
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

3.在util中新建publicapi.js文件

// 获取用户信息
public_api.getUserInfo = params => url.request('/api/usercenter/userDetails',params,'GET',0,true)
// 获取展区
public_api.getLabel = params => url.request('/api/show/getLabel', params, 'POST',1)
// 获取展商
public_api.getContent = params => url.request('/api/getContentByChannelId',params,'GET',1)
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

4.在main.js中修改

import Vue from 'vue'
import  request from './util/request.js'
import api from "./util/publicapi.js"
Vue.prototype.$api = api
  • 1
  • 2
  • 3
  • 4

5.页面中使用

this.$api.getUserInfo({}).then(res=>{
					console.log(res,'用户信息')
					if(res.code ==0){
						let data = res.data
						this.userInfo = {
							id:data.id,
							uname: data.username,
							avatar:data.identificationPhotoDefault
						}
						uni.setStorageSync('userInfo',data)
						
					}
					
				})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/231201
推荐阅读
相关标签
  

闽ICP备14008679号