uniapp request请求封装包含token兼容多端,简单易用

40 篇文章 3 订阅
2 篇文章 0 订阅

1、首先我们在新建好的uniapp项目中新建一个文件夹common,再建一个request.js文件

2. 在request.js放入以下代码


var apiUrl = ''; //放入后台接口的url

// #ifdef H5
var baseUrl = '';
if (process.env.NODE_ENV === 'development') {
	//本地环境,即开发环境
	baseUrl = '/api'
} else {
	//线上环境
	baseUrl = apiUrl
}
// #endif


//封装request请求
const sendRequest = (url, method = 'GET', data = {}, contentType) => {
	//判断header提交数据类型
	let types = '';
	if (method == 'POST' && !contentType) {
		types = 'application/x-www-form-urlencoded'
	} else if (method == 'POST' && contentType) {
		types = contentType
	} else {
		types = 'application/json';
	}

	// #ifdef H5
	var bases = baseUrl + '/' + url;
	// #endif
	
	// #ifndef H5
	var bases = apiUrl + '/' + url;
	// #endif

	var token = uni.getStorageSync('token') || '';
	return new Promise(function(resolve, reject) {
		uni.request({
			url: bases,
			data: data,
			method: method,
			header: {
				'Content-Type': types,
				'Accept': 'application/json, text/javascript, */*; q=0.01',
				'Authorization': token
			},
			success(res) {
				if (res.header.authorization || res.header.Authorization) {
					uni.setStorageSync('token', res.header.authorization || res.header.Authorization);
				} 
				var code = res.statusCode;
				switch (code) {
					case 401:
						uni.showModal({
							title: '登录提示',
							content: '身份已过期,请重新登录后再来操作!',
							success:ress => {
								if (ress.confirm) {
									uni.redirectTo({
										url:'/pages/WxLogin/Accredit'
									})
								}
							}
						})
						break;
					default:
						resolve(res);
						break;
				}
			},
			fail(err) {
				reject(err);
			}
		})
	})
}

module.exports.sendRequest = sendRequest

3、在main.js中全局挂载

import Vue from 'vue'
import App from './App'
import http from './common/js/request.js'


Vue.config.productionTip = false

Vue.prototype.$urls = ""; //线上url接口
Vue.prototype.$http = http;

App.mpType = 'app'

const app = new Vue({
	...App
})
app.$mount()

4、在页面中使用

get方法

//url-后台接口
//data-参数,传递给后台的参数
this.$http.sendRequest(url, 'GET', {
				data:data
}).then(res => {
	//成功回调
}).catch(err => {
    //请求失败
    console.log(err)
})

POST方法

//url-后台接口
//data-参数,传递给后台的参数
this.$http.sendRequest(url,'POST',{
					data:data
				}).then(res => {
					//成功回调
				}).catch(err => {
					//请求失败
				})

有疑问或建议的欢迎在下方留言

  • 7
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
以下是一个较为完整的uniapp网络请求接口封装代码: ```js // 封装请求函数 function request(url, data = {}, method = 'GET') { return new Promise((resolve, reject) => { uni.request({ url, data, method, header: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + uni.getStorageSync('token') }, success: res => { // 请求成功 if (res.statusCode === 200) { resolve(res.data) } else { reject(res) } }, fail: err => { // 请求失败 reject(err) } }) }) } // 定义接口基础地址 const baseUrl = 'https://api.example.com' // 封装接口请求函数 export function login(data) { return request(`${baseUrl}/login`, data, 'POST') } export function getUserInfo(userId) { return request(`${baseUrl}/user/${userId}`) } // ... 还可以继续封装其他接口请求函数 ``` 在上面的代码中,我们在 `request` 函数中添加了一个请求头,用于传递身份验证信息。在每次请求接口时,都会携带一个名为 `Authorization` 的请求头,其值为当前用户的身份验证令牌。这样,在服务端就可以根据身份验证令牌来判断当前用户的身份了。 另外,我们定义了一个 `baseUrl` 常量,用于存储接口的基础地址。这样,在实际使用时,我们只需要在接口请求函数中指定相对地址即可。 在实际使用中,我们可以在需要发送网络请求的地方,直接引入并调用以上封装好的接口请求函数。例如: ```js import { getUserInfo } from '@/api/user' getUserInfo('123456').then(res => { console.log(res) }) ``` 以上代码会调用 `getUserInfo` 函数,向服务器请求 id 为 123456 的用户信息。请求成功后,会将返回的数据打印到控制台中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

余温无痕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值