uniapp项目搭建 请求配置

本文介绍UniApp项目中的请求配置方法及接口调用流程。通过分析`utils/request/index.js`文件,展示了如何配置请求插件、处理请求与响应、编写及调用接口。适合初学者学习。

每个人项目用的请求接口不一样,这里就看下实现思路就好了

请求配置

在 uniapp 当中有封装好的 request 插件, request插件地址
在项目的 utils/request/index.js 中是对请求的配置

utils/request/index.js代码

/**
 * request插件地址:https://ext.dcloud.net.cn/plugin?id=822
 */
import store from '@/store'
import request from './request'
import Config from '@/core/config'

// 后端api地址
const apiUrl = Config.get('apiUrl')

// 可以new多个request来支持多个域名请求
const $http = new request({
   
   
	// 接口请求地址
	baseUrl: apiUrl,
	// 服务器本地上传文件地址
	fileUrl: apiUrl,
	// 服务器上传图片默认url
	defaultUploadUrl: 'upload/image',
	// 设置请求头(如果使用报错跨域问题,可能是content-type请求类型和后台那边设置的不一致)
	header: {
   
   
		'content-type': 'application/json;charset=utf-8'
	},
	// 请求超时时间, 单位ms(默认15000)
	timeout: 15000,
	// 默认配置(可不写)
	config: {
   
   
		// 是否自动提示错误
		isPrompt: true,
		// 是否显示加载动画
		load: true,
		// 是否使用数据工厂
		isFactory: true
	}
})

// 当前接口请求数
let requestNum = 0
// 请求开始拦截器
$http.requestStart = options => {
   
   
	if (options.load) {
   
   
		if (requestNum <= 0) {
   
   
			// 打开加载动画
			uni.showLoading({
   
   
				title: '加载中',
				mask: true
			})
		}
		requestNum += 1
	}
	// 图片上传大小限制
	if (options.method == "FILE" && options.maxSize) {
   
   
		// 文件最大字节: options.maxSize 可以在调用方法的时候加入参数
		const maxSize = options.maxSize
		for (let item of options.files) {
   
   
			if (item.size > maxSize) {
   
   
				setTimeout(() => {
   
   
					uni.showToast({
   
   
						title: "图片过大,请重新上传",
						icon: "none"
					})
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值