uniapp封装request请求

第一步:在你的根文件下创建一个 request 的目录;然后在request文件下创建两个api.js和index.js

第二步封装接口:index .js中:(''https://xxxxx.xxxxx.cn'',改成自己的)

// 全局请求封装
const base_url = 'https://xxxxx.xxxxx.cn'
// 请求超出时间
const timeout = 5000
 
// 需要修改token,和根据实际修改请求头
export default (params) => {
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let header = {
		'Blade-Auth': uni.getStorageSync('token') || '',
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
		'Tenant-Id': uni.getStorageSync('tenantId') || 'xxx', // avue配置相关
		...params.header
	}
	if (method == "post") {
		header = {
			'Content-Type': 'application/json'
		};
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: data,
            timeout,
			success(response) {
				const res = response
				// 根据返回的状态码做出对应的操作
				//获取成功
				// console.log(res.statusCode);
				if (res.statusCode == 200) {
					resolve(res.data);
				} else {
					uni.clearStorageSync()
					switch (res.statusCode) {
						case 401:
							uni.showModal({
								title: "提示",
								content: "请登录",
								showCancel: false,
								success() {
									setTimeout(() => {
										uni.navigateTo({
											url: "/pages/login/index",
										})
									}, 1000);
								},
							});
							break;
						case 404:
							uni.showToast({
								title: '请求地址不存在...',
								duration: 2000,
							})
							break;
						default:
							uni.showToast({
								title: '请重试...',
								duration: 2000,
							})
							break;
					}
				}
			},
			fail(err) {
				console.log(err)
				if (err.errMsg.indexOf('request:fail') !== -1) {
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					uni.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);
 
			},
			complete() {
				// 不管成功还是失败都会执行
				uni.hideLoading();
				uni.hideToast();
			}
		});
	}).catch(() => {});
};

api.js中:(这两个是我自己的接口封装示例,改成自己的)

// 引入 request 文件
import request from './index.js'
 
// 获取学习列表详细信息登录
export const getLogin = ({ iphone, pwd }) => {
  return request({
    url: `/index.php/index/User/webLogin`,
    method: 'post',
    data: {
      iphone,
      pwd
    }
  });
};
// web用户的注册和修改接口
export const getZhuCe = ({ iphone, pwd ,webname}) => {
  return request({
    url: `/index.php/index/User/addWebuser`,
    method: 'post',
    data: {
      iphone,
      pwd,
	  webname
    }
  });
};

以下是我在页面中使用接口的示例代码

这是第一个接口里的使用实例代码:

<template>
	<view class="">
		<image class="images" src="https://img.zcool.cn/community/013b625c91fd55a8012141680487b8.gif" mode=""></image>
		<text class="text1">欢迎登录</text>
		<view class="viewOne">
			<image class="imageOne" src="../../static/BAvSeQLYg2ABWvaG3hAUBtUDc0ERjQ0IWp7bE6z4BfJAkiX0uDyl0AAAAASUVORK5CYII=.png" mode=""></image>
		<input class="itpOne" placeholder="请输入手机号" type="text" v-model="phoneNumber">
		</view>
		<view class="viewTwo">
			<image class="imageOne" src="../../static/AX30tZW6dLuCtAAAAAElFTkSuQmCC.png" mode=""></image>
		<input class="itpOne" placeholder="请输入密码" type="text" v-model="password">
		</view>
		<button class="buttonss" @click="btn()">登 录</button>
		
<view class="viewThree">
	
			<label>
				<checkbox /><text></text>
			</label>
我已阅读并同意<text class="text2">使用条款、隐私政策</text>和<text class="text2">使用规范</text>
		
</view>

	<navigator url="/pages/ZhuCe/ZhuCe" class="viewFour">没有账号?去注册</navigator>
	

	</view>
</template>

<script>
import { getLogin } from '@/request/api.js';

export default {
  data() {
    return {
      phoneNumber: '',
      password: ''
    };
  },
  methods: {
   btn() {
       uni.showLoading({
         title: '登录中...',
         mask: true
       });
   
       getLogin({ iphone: this.phoneNumber, pwd: this.password })
	   .then(res => {
	     uni.hideLoading();
	   //   console.log('Response:', res);
	   
	     let isLoginSuccess = false;
	     if ('webid' in res.data) {
	       isLoginSuccess = true;
	     }
	   
	     if (isLoginSuccess) {
	       console.log('登录成功:', res.data);
	       uni.reLaunch({
	         url: '/pages/index/index'
	       });
	     } else {
	       console.error('登录失败,服务器返回:', res.data);
	       uni.showToast({
	         title: res.data.webusername + ',登录失败',
	         icon: 'none'
	       });
	     }
	   })
    
         .catch(err => {
           uni.hideLoading();
           uni.showToast({
             title: '网络错误,请检查您的网络设置',
             icon: 'none'
           });
         });
     }
  },
  mounted() {
    // 页面加载时的初始化代码
  }
};
</script>

这是第二个接口里的使用实例代码:

<template>
	<view class="">
		<image class="images" src="https://img.zcool.cn/community/01e8985ef31d5ea8012066212846ed.gif" mode=""></image>
		<text class="text1">欢迎注册</text>
		<view class="viewOne">
			<image class="imageOne" src="/static/9hHG6FQ4vmAAAAAElFTkSuQmCC.png" mode=""></image>
		<input class="itpOne" placeholder="请输入用户名" type="text" v-model="webname">
		</view>
		<view class="viewTwo">
			<image class="imageOne" src="../../static/BAvSeQLYg2ABWvaG3hAUBtUDc0ERjQ0IWp7bE6z4BfJAkiX0uDyl0AAAAASUVORK5CYII=.png" mode=""></image>
		<input class="itpOne" placeholder="请输入手机号" type="text" v-model="iphone">
		</view>
		<view class="viewTwo">
			<image class="imageOne" src="../../static/AX30tZW6dLuCtAAAAAElFTkSuQmCC.png" mode=""></image>
		<input class="itpOne" placeholder="请输入密码" type="text" v-model="pwd">
		</view>
		<button class="buttonss"  @click="zhuce">注 册</button>
		
<view class="viewThree">
	
			<label>
				<checkbox /><text></text>
			</label>
我已阅读并同意<text class="text2">使用条款、隐私政策</text>和<text class="text2">使用规范</text>
		
</view>

	<navigator url="/pages/ShouYe/ShouYe" class="viewFour">已有账号?去登录</navigator>
	

	</view>
</template>

<script>
	import { getZhuCe } from '@/request/api.js';
	export default{
		data(){
			return{
				webname: '',
							iphone: '',
							pwd: ''
			}
		},
		methods:{
			zhuce() {
			
			getZhuCe({ iphone: this.iphone, pwd: this.pwd, webname: this.webname })
				.then(res => {
					if (res.data.code === 0) {
						uni.showToast({
							title: '注册成功',
							icon: 'success'
						});
						// 注册成功后,可以选择跳转到登录页面或首页
						uni.switchTab({
							url: '/pages/ShouYe/ShouYe'
						});
					} 
				})
				.catch(err => {
					uni.showToast({
						title: '网络错误,请检查您的网络设置',
						icon: 'none'
					});
				});
		}
		}
	}
</script>

相关推荐

  1. Python requests请求封装

    2024-07-17 06:58:03       53 阅读
  2. uniapp request.js封装例子

    2024-07-17 06:58:03       47 阅读
  3. uniapp 接口请求封装

    2024-07-17 06:58:03       24 阅读
  4. uniapp 请求封装

    2024-07-17 06:58:03       25 阅读
  5. vue 封装request请求 多域名访问

    2024-07-17 06:58:03       47 阅读
  6. uniapp+axios请求封装

    2024-07-17 06:58:03       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 06:58:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 06:58:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 06:58:03       57 阅读
  4. Python语言-面向对象

    2024-07-17 06:58:03       68 阅读

热门阅读

  1. ubuntu系统Docker常用命令

    2024-07-17 06:58:03       22 阅读
  2. Web前端-Web开发HTML基础2-list

    2024-07-17 06:58:03       25 阅读
  3. Qt中qApp简单介绍

    2024-07-17 06:58:03       26 阅读
  4. 2407-mysql笔记

    2024-07-17 06:58:03       18 阅读
  5. opencv—常用函数学习_“干货“_10

    2024-07-17 06:58:03       30 阅读
  6. Windows图形界面(GUI)-DLG-C/C++ - 静态控件(Static)

    2024-07-17 06:58:03       25 阅读
  7. 掌握Core Data:Xcode中的数据管理利器

    2024-07-17 06:58:03       26 阅读
  8. CMD命令fc(File Compare)

    2024-07-17 06:58:03       26 阅读
  9. Linux下安装PostgreSQL.16.3

    2024-07-17 06:58:03       22 阅读
  10. Android 桌面小组件使用

    2024-07-17 06:58:03       22 阅读