uniapp-第三方网络请求

 背景

小程序项目中, 不支持 axios, 而且原生的 wx.request() API功能较为简单, 不支持拦截器等全局定制的功能. 因此,
建议在 uni-app 项目中使用 @escook/request-miniprogram 第三方包发起网络数据请求

 安装

npm i @escook/request-miniprogram -S 下载网络请求包

main.js

// 导入网络请求的包
import {
	$http
} from '@escook/request-miniprogram'
uni.$http = $http
// 请求的根路径
$http.baseUrl = 'https://api-hmugo-web.itheima.net'
// 请求拦截器
$http.beforeRequest = function(options) {
	uni.showLoading({
		title: '数据加载中...'
	})
	// 判断请求的是否为有权限的 API 接口
	if (options.url.indexOf('/my/') !== -1) {
		// 为请求头添加身份认证字段
		options.header = {
			// 字段的值可以直接从 vuex 中进行获取
			Authorization: store.state.m_user.token,
		}
	}
}
// 响应拦截器
$http.afterRequest = function() {
	uni.hideLoading()
}

 使用

const {
					data: res2
				} = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {
					order_number: orderNumber
				})
				// 2.2 预付订单生成失败
				if (res2.meta.status !== 200) return uni.$showError('预付订单生成失败!')
				// 2.3 得到订单支付相关的必要参数
				const payInfo = res2.message.pay

封装接口 

 1.在utils文件夹下新建config.js

var url;
if (process.env.NODE_ENV === 'development') {
	console.log('开发环境')
	url = 'https://www.uinav.com'
} else {
	console.log('生产环境')
	url = 'https://www.uinav.com'
}
export const baseUrl = url

2.在utils文件夹下新建request.js

import {
	$http
} from '@escook/request-miniprogram'

import {
	baseUrl
} from "@/utils/config.js"

const service = $http
// 请求的根路径
 $http.baseUrl = baseUrl
// 请求拦截器
$http.beforeRequest = function(options) {
	uni.showLoading({
		title: '数据加载中...'
	})
	// 判断请求的是否为有权限的 API 接口
	if (options.url.indexOf('/my/') !== -1) {
		// 为请求头添加身份认证字段
		options.header = {
			// 字段的值可以直接从 vuex 中进行获取
			Authorization: store.state.m_user.token,
		}
	}
}
// 响应拦截器
$http.afterRequest = function() {
	uni.hideLoading()
}

export default service

3.在apis文件下新建login.js

 // 登录
 export function login(data) {
   return request.post('/login', data)
 
 }
 
 // 获取轮播图
 export function getswiperdata(data) {
   return request.get('/api/public/v1/home/swiperdata', data)
 
 }
 

4.在页面中使用接口

	import {
		login
	} from "@/apis/login.js"
---------------------------------------

var data2 = {
					username: this.phone,
					password: this.password
				}
				const {
					data
				} = await login(data2);
				console.log(data);
				if (data.code !== 200){
					uni.showToast({
						title: data.msg,
					});
					
				}   else{
					uni.showToast({
						title: "登录成功",
					});
				}

猜你喜欢

转载自blog.csdn.net/zxc472504515/article/details/125455769