uniapp - third-party network request

 background

In mini program projects, axios is not supported, and the original wx.request() API function is relatively simple, and does not support global customization functions such as interceptors. Therefore, it is recommended to use @escook/request
-miniprogram third-party in uni-app projects Packet initiates network data request

 Install

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()
}

 use

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

package interface 

 1. Create a new config.js under the utils folder

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. Create a new request.js under the utils folder

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. Create a new login.js under the apis file

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

4. Use the interface in the page

	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: "登录成功",
					});
				}

Guess you like

Origin blog.csdn.net/zxc472504515/article/details/125455769