uniapp封装request请求

642 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天

  • pages文件夹同级下创建一个utils文件作为请求公共文件
  • utils文件夹下面创建一个request.js和api.js
  • request.js为封装的request请求
  • api.js为接口
  • 根据项目需求 可通过模块划分不同模块的接口文件,本次仅举例api.js一个接口文件
  1. 以下为request.js封装方法
// 封装请求接口
let baseUrl
switch (process.env.NODE_ENV) {
	// 开发环境的联调地址
    case 'development':
        // 公共的地址开发  可根据联调后台 进行更改
        baseUrl = ''
        break
	// 生产环境地址
    case 'production':
        baseUrl = ''
        break
    default:
        // 开发环境地址
        baseUrl = ''
}
// 封装的uni.request请求
const sendRequest = (url, method = 'GET', data = {}, contentType) => {
	//判断header提交数据类型
	let types = '';
	if (method == 'POST' && !contentType) {
	// 最常见的 POST 提交数据的方式。浏览器的原生 form 表单,如果不设置 enctype 属性,
        //就会以 application/x-www-form-urlencoded 方式提交数据。数据按照 key1=val1&key2=val2 的方式进行编码,
	//key 和 val 都进行了 URL 转码,不支持文件,一般用于表单提交
		types = 'application/x-www-form-urlencoded'
	} else if (method == 'POST' && contentType) {
		// multipart/form-data   支持文件上传的格式,一般需要上传文件的表单则用该类型
		types = contentType
	} else {
		// 其他json数据格式请求 
		types = 'application/json';
	}
 
	// #ifdef H5
	var bases = baseUrl + '/' + url;
	// #endif
 
	var token = uni.getStorageSync('token') || '';
	uni.showLoading({ title: '加载中...', mask: true })
	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) {
                        uni.hideLoading()
                        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

  1. 以下为api.js
// 该文件放接口 
// 引入封装的request.js文件
import sendRequest from "./request";

// 用户信息方法接口
export function getUserInfo() {
    return sendRequest({
        url: "/app-user/getUser/99064838", // 这个地址是去掉公共地址剩下的地址  也就是接口
        method: "GET", // 请求方式 支持多种方式  get post put delete 等等
        data, //发送请求要配置的参数 无参数的情况下也可以不写
        //contentType:'', // contentType 用于post请求情况下有所区分  get请求可不写
    });
},
export function postList(data) {
    return sendRequest({
        url: "/app-user/getUser/99064838", // 这个地址是去掉公共地址剩下的地址  也就是接口
        method: "POST", // 请求方式 支持多种方式  get post put delete 等等
        data, //发送请求要配置的参数 无参数的情况下也可以不写
        contentType:'', //  如果是表单提交 不涉及文件上传 可不写
    });
},
export function postListForm(data) {
    return sendRequest({
        url: "/app-user/getUser/99064838", // 这个地址是去掉公共地址剩下的地址  也就是接口
        method: "POST", // 请求方式 支持多种方式  get post put delete 等等
        data, //发送请求要配置的参数 无参数的情况下也可以不写
        contentType:'multipart/form-data', //  涉及文件上传需添加
    });
},
// 直接get获取
export function getAllList(){
    return sendRequest({
        url: `v1/accident/product/list`,
        method: "GET"
    })
}
export function putList(data) {
    return sendRequest({
        url: "/app-user/getUser/99064838", // 这个地址是去掉公共地址剩下的地址  也就是接口
        method: "PUT", // 请求方式 支持多种方式  get post put delete 等等
        data //发送请求要配置的参数 无参数的情况下也可以不写
        // contentType:'', //  涉及文件上传需添加  post情况下需要区分
    });
},
export function deleteList(data) {
    return sendRequest({
        url: "/app-user/getUser/99064838", // 这个地址是去掉公共地址剩下的地址  也就是接口
        method: "DELETE", // 请求方式 支持多种方式  get post put delete 等等
        data, //发送请求要配置的参数 无参数的情况下也可以不写
        // contentType:'', //  涉及文件上传需添加 post情况下需要区分
    });
}
  • 页面中使用
  • 哪个页面使用,引入接口文件即可
<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view>
		<button type="primary" @click="get1">get1请求</button>
		<button type="primary" @click="get2">get2请求</button>
		<button type="primary" @click="post1">post1请求</button>
		<button type="primary" @click="post2">post2请求</button>
		<button type="primary" @click="put">put请求</button>
		<button type="primary" @click="deleteone">delete请求</button>
	</view>
</template>

<script>
        // 引入api.js中的接口
        import { getUserInfo, getAllList, postList, postListForm, putList, deleteList } from "../../utils/api";
	export default {
		data() {
                    return {
                        title: 'Hello',
                        arrData:[]
                    }
		},
		onLoad() {

		},
		methods: {
                    // get请求携带参数
                    get1() {
                        let params = {
                            isName: "",
                            pageIndex: 10,
                            pageSize: 1,
                            productType: ""
                        }
                        getUserInfo(params).then(res => {
                            console.log('res', res);
                            this.arrData = res.data
                        })
                    },
                    get2() {
                        // get请求不携带参数
                        getAllList().then(res => {
                            console.log('res', res);
                            this.arrData = res.data
                        })
                    },
                    post1(){
                        // post请求 不涉及文件上传
                        let params = {
                            isName: "",
                            pageIndex: 10,
                            pageSize: 1,
                            productType: ""
                        }
                        postList(params).then(res=>{
                            console.log('res', res);
                            this.arrData = res.data
                        })
                    },
                    post2(){
                        // post请求 不涉及文件上传
                        let params = {
                            isName: "",
                            pageIndex: 10,
                            pageSize: 1,
                            productType: ""
                        }
                        postListForm(params).then(res=>{
                            console.log('res', res);
                            this.arrData = res.data
                        })
                    },
                    put(){
                        // put请求
                        let params = {
                            isName: "",
                            productType: ""
                        }
                        putList(params).then(res=>{
                            console.log('res', res);
                            this.arrData = res.data
                        })
                    },
                    deleteone() {
                        // delete请求
                        let params = {
                            id:''
                        }
                        deleteList(params).then(res=>{
                            console.log('res', res);
                        })
                    }
			
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>