uni-app封装一个request请求

简介: uni-app封装一个request请求

在上一篇文章里面,写到使用uni.request请求的方法

https://www.jianshu.com/p/bc62c9e1beed

getList() {         
                uni.request({
                    url: "https://unidemo.dcloud.net.cn/api/news",                  
                    method: 'get',
                    dataType: 'json',
                    success: (res) => {
                        console.log(res.data);
                        this.productList = res.data;
                    },                  
                });
            },

但是实际做项目的时候,会发现每个界面都要重复的写这些,看起来重复又啰嗦,心情就十分的不美丽了。

如果不封装那么我们会面临几个不方便的地方:

请求头每次网络请求都要单独设置
返回数据的正确性判断每次都要重复大量代码
返回数据格式有变化需要修改所有网络请求的地方

那么,该怎么使用uni-app封装一个request请求?步骤很简单,且听我一一道来。

注意:使用的例子,来自于这篇文章的相关的代码,修改封装请求是基于这个文章里面代码。进行相关的修改的。

步骤如下:

1、项目下新建common文件夹,再创建request.js文件


2、打开request.js文件,开始写封装的代码

思路很简单

定义域名:baseUrl;

定义方法:api;

通过promise异步请求,最后导出方法。

request.js参考代码如下

const baseUrl = 'https://unidemo.dcloud.net.cn'   
const request = (url = '', date = {}, type = 'GET', header = {
}) => {
    return new Promise((resolve, reject) => {
        uni.request({
            method: type,
            url: baseUrl + url,
            data: date,
            header: header,
            dataType: 'json',         
        }).then((response) => {
            setTimeout(function() {
                uni.hideLoading();
            }, 200);
            let [error, res] = response;        
            resolve(res.data);
        }).catch(error => {
            let [err, res] = error;
            reject(err)
        })
    });
}
export default request

3、在main.js全局注册

import request from 'common/request.js'
Vue.prototype.$request = request

 

4、页面调用

this.$request('/api/news', {
// 传参参数名:参数值,如果没有,就不需要传
}).then(res => {
// 打印调用成功回调
console.log(res)
})

页面调用的index.vue

<template>
    <view>
        <uni-list v-for="(item,index) in productList" :key="index">
            <uni-list-item :title="item.author_name" :note="item.title"></uni-list-item>
        </uni-list>
    </view>
</template>
<script>
    import uniList from "@/components/uni-list/uni-list.vue"
    import uniListItem from "@/components/uni-list-item/uni-list-item.vue"
    export default {
        components: {
            uniList,
            uniListItem
        },
        data() {
            return {
                productList: [],
            };
        },
        onLoad() {
            this.getList();
        },
        methods: {
            getList() {
                this.$request('/api/news', {
                    // 传参参数名:参数值,如果没有,就不需要传
                    // "username": "john",
                    // "key": this.searchValue
                }).then(res => {
                    // 打印调用成功回调
                    console.log(res)
                    this.productList = res;
                })
            },
        }
    }
</script>
<style>
</style>

成功显示

 

好了,完结,散花,准备睡觉!!

各位路过的小哥哥,小姐姐,喜欢的就点个赞呗。


相关文章
|
2月前
|
存储 BI Android开发
全开源仿第八区H5APP封装打包分发系统源码
全开源仿第八区H5APP封装打包分发系统源码
97 4
|
2月前
|
Go 开发者
【应用服务 App Service】App Service发生错误请求时,如何查看IIS Freb日志,从中得知错误所发生的模块,请求中所携带的Header信息
【应用服务 App Service】App Service发生错误请求时,如何查看IIS Freb日志,从中得知错误所发生的模块,请求中所携带的Header信息
|
2月前
|
网络协议 安全 前端开发
【应用服务 App Service】Azure 应用服务测试网络访问其他域名及请求超时限制(4分钟 ≈ 230秒)
【应用服务 App Service】Azure 应用服务测试网络访问其他域名及请求超时限制(4分钟 ≈ 230秒)
|
2月前
|
存储 网络安全 数据中心
【Azure 存储服务】App Service 访问开启防火墙的存储账号时遇见 403 (This request is not authorized to perform this operation.)
【Azure 存储服务】App Service 访问开启防火墙的存储账号时遇见 403 (This request is not authorized to perform this operation.)
【Azure 存储服务】App Service 访问开启防火墙的存储账号时遇见 403 (This request is not authorized to perform this operation.)
|
2月前
|
Java Go Windows
【应用服务 App Service】App Service中上传文件/图片(> 2M)后就出现500错误(Maximum request length exceeded).
【应用服务 App Service】App Service中上传文件/图片(> 2M)后就出现500错误(Maximum request length exceeded).
|
2月前
|
API C#
【Azure App Service】验证App Service接受HTTP 2.0请求
【Azure App Service】验证App Service接受HTTP 2.0请求
|
2月前
|
API 持续交付 数据安全/隐私保护
【Azure ACR+App Service】ACR WebHook请求App Service时遇见 401 Unauthorized
【Azure ACR+App Service】ACR WebHook请求App Service时遇见 401 Unauthorized
|
2月前
|
数据中心 容器
【Azure 应用服务】在创建App Service时,遇见“No available instances to satisfy this request. App Service is attempting to increase capacity.”错误
【Azure 应用服务】在创建App Service时,遇见“No available instances to satisfy this request. App Service is attempting to increase capacity.”错误
|
2月前
|
应用服务中间件 Linux 网络安全
【Azure 应用服务】PHP应用部署在App Service for Linux环境中,上传文件大于1MB时,遇见了413 Request Entity Too Large 错误的解决方法
【Azure 应用服务】PHP应用部署在App Service for Linux环境中,上传文件大于1MB时,遇见了413 Request Entity Too Large 错误的解决方法
|
2月前
|
JSON 数据格式 索引
【Azure Developer】Azure Logic App 示例: 解析 Request Body 的 JSON 的表达式? triggerBody()?
【Azure Developer】Azure Logic App 示例: 解析 Request Body 的 JSON 的表达式? triggerBody()?