uni-app入门教程(5)接口的基本使用

CuterCorley
• 阅读 1222

前言

本文主要介绍uni-app提供的一些基础接口,包括:网络请求接口,用于通过指定的请求方法,携带特定的数据,向特定的地址请求并返回请求结果;图片处理接口,包括选择、预览、获取信息、保存到本地等接口;文件处理接口,包括文件上传和下载接口;数据缓存接口,包括以同步或异步的方式保存、获取或删除数据的接口。

一、网络请求

小程序要想正常运转,都需要与服务器端进行数据交互,一般都通过接口实现。 数据交互一般都会通过网络请求接口实现。

uni.request(OBJECT)是用于发起网络请求的接口。

OBJECT常见参数如下: 参数名| 类型| 必填与否| 默认值| 说明 -----|-----|-----|-----|----- url |String| 是|无| 开发者服务器接口地址
data| Object/String/ArrayBuffer| 否|无| 请求的参数 header| Object| 否|无| 设置请求的 header,不能设置 Referer method| String| 否| GET|请求方法,包括GET、POST、PUT、DELETE等方法
timeout| Number| 否| 60000| 超时时间,单位 ms dataType| String| 否| json| 如果设为 json,会尝试对返回的数据做一次 JSON.parse
responseType| String| 否| text| 设置响应的数据类型。合法值:text、arraybuffer success| Function| 否|无| 收到开发者服务器成功返回的回调函数
fail| Function| 否|无| 接口调用失败的回调函数
complete| Function| 否| 无| 接口调用结束的回调函数(调用成功、失败都会执行)

使用GET方法进行普通请求,index.vue如下:

<template>
    <view>
        {{res}}
    </view>
</template>

<script>
    export default {
        data() {
            return {
                res:''
            }
        },
        onLoad() {
            uni.request({
                url:'https://demo.hcoder.net',
                method: 'GET',
                success:function(res){
                    console.log(res)
                }
            })
        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,请求后返回了data数据。

说明: 在各个小程序平台运行时,网络相关的API在使用前需要配置域名白名单,因此在使用小程序进行测试时,需要在微信开发者中心设置域名,或者在项目的本地配置中不校验合法域名,如下: uni-app入门教程(5)接口的基本使用

再请求json数据和使用POST方法请求,如下:

<template>
    <view>
        {{res}}
    </view>
</template>

<script>
    export default {
        data() {
            return {
                res: ''
            }
        },
        onLoad() {
            const request1 = uni.request({
                url: 'https://demo.hcoder.net/index.php?m=getJson',
                success: function(res) {
                    console.log(res.data);
                }
            });
            //
            const request2 = uni.request({
                url: 'https://demo.hcoder.net/index.php',
                data: {
                    name: 'Corley',
                    'age': 18
                },
                method: "POST",
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                success: function(res) {
                    console.log(res.data);
                }
            });
        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {}
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,也返回了数据。

二、图片处理

1.chooseImage(OBJECT)

从本地相册选择图片或使用相机拍照。

OBJECT常见参数如下: 参数名| 类型| 必填与否 |说明 -----|-----|-----|----- count| Number| 否 |最多可以选择的图片张数,默认9| count 值在 H5 平台的表现,基于浏览器本身的规范 sizeType| Array| 否 original 原图,compressed 压缩图,默认二者都有 extension| Array| 否| 根据文件拓展名过滤,每一项都不能是空字符串。默认不过滤。 sourceType |Array| 否| album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
success| Function| 是| 成功则返回图片的本地文件路径列表 tempFilePaths
fail| Function| 否| 接口调用失败的回调函数 小程序、App complete |Function |否| 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template>
    <view>
        <button type="primary" @click="img">上传图片</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
            }
        },
        onLoad() {

        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            img: function(){
                uni.chooseImage({
                    count: 9,
                    sizeType:"compressed",
                    success:function(res){
                        console.log(res)
                    }
                })
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,上传成功后,结果返回了临时图片的路径链接。

2.previewImage(OBJECT)

预览图片。

OBJECT常见参数如下: 参数名| 类型| 必填| 说明 -----|-----|-----|----- current| String/Number|因情况而定|当前显示图片的链接/索引值,不填或填写的值无效则为 urls 的第一张 urls| Array| 是| 需要预览的图片链接列表
indicator| String |否| 图片指示器样式,可取值:"default" - 底部圆点指示器; "number" - 顶部数字指示器; "none" - 不显示指示器 loop| Boolean| 否| 是否可循环预览,默认值为 false longPressActions| Object| 否| 长按图片显示操作菜单,如不填默认为保存相册 success| Function| 否| 接口调用成功的回调函数
fail| Function| 否| 接口调用失败的回调函数
complete| Function| 否 |接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template>
    <view>
        <button type="primary" @click="img">上传图片</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
            }
        },
        onLoad() {

        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            img: function(){
                uni.chooseImage({
                    count: 9,
                    sizeType:"compressed",
                    success:function(res){
                        console.log(res);
                        uni.previewImage({
                            urls: res.tempFilePaths,
                        })
                    }
                })
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,在调用uni.chooseImage上传图片后,成功时的回调函数中再调用uni.previewImage,即可实现预览。

被预览的图片链接,除了可以是uni.chooseImage上传生成的内部临时图片,还可以是自定义的外部图片,如下:

<template>
    <view>
        <button type="primary" @click="img">显示图片</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
            }
        },
        onLoad() {

        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            img: function(){
                uni.previewImage({
                    urls: ['https://bkimg.cdn.bcebos.com/pic/95eef01f3a292df56f9e63a6b2315c6034a87320?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1', 'https://bkimg.cdn.bcebos.com/pic/83025aafa40f4bfb112d51e70d4f78f0f6361880?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1', 'https://bkimg.cdn.bcebos.com/pic/622762d0f703918f8453f4795f3d269758eec487?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1']
                })
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,外部图片也可以正常显示。

3.getImageInfo(OBJECT)

获取图片信息。

OBJECT常见参数和含义如下: 参数名| 类型| 必填| 说明 -----|-----|-----|----- src| String| 是| 图片的路径,可以是相对路径、临时文件路径、存储文件路径、网络图片路径 success| Function| 否| 接口调用成功的回调函数 fail| Function| 否| 接口调用失败的回调函数 complete |Function| 否| 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template>
    <view>
        <button type="primary" @click="img">获取图片信息</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
            }
        },
        onLoad() {

        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            img: function(){
                uni.getImageInfo({
                    src: 'https://cn.bing.com/th?id=OHR.HolidayNubble_ZH-CN8122183595_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp',
                    success: function(res){
                        console.log(res)
                    }
                })
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,获取到了图片的大小、类型和方向等信息。

4.saveImageToPhotosAlbum(OBJECT)

保存图片到系统相册。

OBJECT常见参数如下: 参数名| 类型| 必填| 说明 -----|-----|-----|----- filePath| String| 是| 图片文件路径,可以是临时文件路径也可以是永久文件路径,不支持网络图片路径 success| Function| 否| 接口调用成功的回调函数 fail |Function| 否| 接口调用失败的回调函数 complete |Function| 否| 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template>
    <view>
        <button type="primary" @click="img">上传图片并下载</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {}
        },
        onLoad() {

        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            img: function() {
                uni.chooseImage({
                    count: 9,
                    sizeType: "compressed",
                    success: function(res) {
                        console.log(res);
                        uni.saveImageToPhotosAlbum({
                            filePath: res.tempFilePaths[0],
                            success:function(){
                                console.log('save success');
                            }
                        })
                    }
                })
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,可以实现将图片保存到本地,并且图片信息一致。

三、文件上传和下载

1.uploadFile(OBJECT)

将本地资源上传到开发者服务器,客户端发起一个 POST 请求,其中 content-type 为 multipart/form-data

OBJECT常见参数如下: 参数名| 类型| 必填| 说明 -----|-----|-----|----- url| String| 是| 开发者服务器 url
files| Array| 否| 需要上传的文件列表。使用 files 时,filePath 和 name 不生效 fileType| String| 平台之间存在关系| 文件类型,image/video/audio file |File| 否| 要上传的文件对象 filePath |String| 是| 要上传文件资源的路径 name |String| 是 |文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
header| Object| 否| HTTP 请求 Header, header 中不能设置 Referer
timeout |Number|否| 超时时间,单位 ms formData| Object| 否| HTTP 请求中其他额外的 form data
success |Function| 否| 接口调用成功的回调函数
fail |Function| 否| 接口调用失败的回调函数
complete| Function| 否| 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template>
    <view>
        <button type="primary" @click="img">上传文件</button>
        <progress :percent="percent" stroke-width="20" />
    </view>
</template>

<script>
    var _self;
    export default {
        data() {
            return {
                percent: 0
            }
        },
        onLoad() {
            _self = this;
        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            img: function() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ["compressed"],
                    success: function(res) {
                        var imgFile = res.tempFilePaths[0];
                        console.log(imgFile);
                        var uper = uni.uploadFile({
                            url: "https://demo.hcoder.net/index.php?c=uperTest",
                            filePath: imgFile,
                            name: 'file',
                            success:function(upres){
                                console.log(upres)
                            }
                        });
                        uper.onProgressUpdate(function(prores){
                            _self.percent = prores.progress;
                            console.log('上传进度'+prores.progress);
                            console.log('已上传数据长度'+prores.totalBytesSent);
                            console.log('预期需要上传数据总长度'+prores.totalBytesExpectedToSend);
                        })
                    }
                })
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,在上传图片文件之后,获取到了实时的上传进度、并在进度条中同步显示。

除了使用uni.uploadFile(OBJECT),还可以使用更好的APIuniCloud.uploadFile,uniCloud提供了免费CDN和更好的易用性,包括安全的cdn直传。

2.downloadFile(OBJECT)

下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。

OBJECT常见参数如下: 参数名| 类型| 必填与否| 说明 -----|-----|-----|----- url |String| 是| 下载资源的 url
header |Object| 否| HTTP 请求 Header, header 中不能设置 Referer timeout |Number| 否| 超时时间,单位 ms success| Function| 否| 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'}
fail |Function| 否| 接口调用失败的回调函数
complete |Function| 否| 接口调用结束的回调函数(调用成功、失败都会执行)

index.vue如下:

<template>
    <view>
        <button type="primary" @click="img">下载文件</button>
        <progress :percent="percent" stroke-width="20" />
    </view>
</template>

<script>
    var _self;
    export default {
        data() {
            return {
                percent: 0,
            }
        },
        onLoad() {
            _self = this;
        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            img: function() {
                const down = uni.downloadFile({
                    url: 'https://bkimg.cdn.bcebos.com/pic/95eef01f3a292df56f9e63a6b2315c6034a87320?x-bce-process=image/resize,m_lfit,w_220,h_220,limit_1',
                    success: function(res) {
                        if (res.statusCode === 200) {
                            console.log(res);
                            uni.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success: function() {
                                    console.log('save success');
                                }
                            })
                        }
                    }
                });
                down.onProgressUpdate((prores) => {
                    _self.percent = prores.progress;
                    console.log('下载进度' + prores.progress);
                    console.log('已下载数据长度' + prores.totalBytesWritten);
                    console.log('预期下载数据总长度' + prores.totalBytesExpectedToWrite);
                });
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以下载图片到本地并保存。

四、数据缓存

在APP或者小程序中,可以利用本地存储来保存一些数据,比如用户登录数据,在使用用户名密码或者第三方登录方式进行登录后,会将用户信息保存到服务器端,会将用户id和用户随机码(与用户匹配)以键值对的形式到本地,每次与远程进行交互时,都会将保存下来的用户数据发送到远程进行校验。

1.setStorage(OBJECT)

将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口,可以在存储的同时进行其他操作。

OBJECT参数及其意义如下: 参数名| 类型| 必填与否| 说明 -----|-----|-----|----- key |String| 是| 本地缓存中的指定的 key data |Any| 是| 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象 success| Function| 否| 接口调用成功的回调函数 fail |Function| 否| 接口调用失败的回调函数 complete |Function| 否| 接口调用结束的回调函数(调用成功、失败都会执行)

2.setStorageSync(KEY,DATA)

将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口,需要在数据存储完成之后才能进行其他操作。

参数及其意义如下: 参数名| 类型| 必填与否| 说明 -----|-----|-----|----- key |String| 是| 本地缓存中的指定的 key data| Any| 是| 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象

在使用uni.setStorageSync(KEY,DATA)存储数据时,需要使用try...catch...语句块捕捉异常。

setStoragesetStorageSync的简单使用如下:

<template>
    <view>
        <button type="primary" @click="asyncsave">异步保存数据</button>
        <button type="primary" @click="syncsave">同步保存数据</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {}
        },
        onLoad() {
        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            asyncsave: function(){
                uni.setStorage({
                    key: 'name',
                    data: 'Corley',
                    fail:function(){
                        console.log('Save failed')
                    }
                });
            },
            syncsave: function(){
                try{
                    uni.setStorageSync('age', '18')
                }catch(e){
                    console.log(e)
                }
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以看到,两种方式都将数据保存下来。

3.getStorage(OBJECT)

从本地缓存中异步获取指定 key 对应的内容。

OBJECT 参数及其含义如下: 参数名| 类型| 必填与否| 说明 -----|-----|-----|----- key |String| 是| 本地缓存中的指定的 key success| Function| 是| 接口调用的回调函数,res = {data: key对应的内容} fail |Function| 否| 接口调用失败的回调函数 complete |Function| 否| 接口调用结束的回调函数(调用成功、失败都会执行)

4.getStorageSync(KEY)

从本地缓存中同步获取指定 key 对应的内容。

参数及其含义如下: 参数名| 类型| 必填与否| 说明 -----|-----|-----|----- key |String |是| 本地缓存中的指定的 key

getStorageSync也需要使用try...catch...语句块捕捉异常。

getStoragegetStorageSync的简单使用如下:

<template>
    <view>
        <button type="primary" @click="asyncget">异步获取数据</button>
        <button type="primary" @click="syncget">同步获取数据</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {}
        },
        onLoad() {
            uni.setStorage({
                key: 'name',
                data: 'Corley',
                fail:function(){
                    console.log('Save failed')
                }
            });
            try{
                uni.setStorageSync('age', '18')
            }catch(e){
                console.log(e)
            }
        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            asyncget: function(){
                uni.getStorage({
                    key: 'age',
                    success: function (res) {
                        console.log('age:'+res.data);
                    }
                })
            },
            syncget: function(){
                try{
                    const name = uni.getStorageSync('name');
                    if (name){
                        console.log('name:'+name);
                    }
                }catch(e){
                    console.log(e);
                }
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

可以获取到之前保存下来的数据。

5.removeStorage(OBJECT)

从本地缓存中异步移除指定 key。

OBJECT 参数及其含义如下: 参数名| 类型| 必填与否| 说明 -----|-----|-----|----- key| String| 是| 本地缓存中的指定的 key success| Function| 是| 接口调用的回调函数 fail |Function| 否| 接口调用失败的回调函数 complete| Function| 否| 接口调用结束的回调函数(调用成功、失败都会执行)

6.removeStorageSync(KEY)

从本地缓存中同步移除指定 key。

参数说明: 参数名| 类型| 必填与否| 说明 -----|-----|-----|----- key| String| 是| 本地缓存中的指定的 key

removeStorageremoveStorageSync的简单使用如下:

<template>
    <view>
        <button type="primary" @click="asyncremove">异步删除数据</button>
        <button type="primary" @click="syncremove">同步删除数据</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {}
        },
        onLoad() {
            uni.setStorage({
                key: 'name',
                data: 'Corley',
                fail:function(){
                    console.log('Save failed')
                }
            });
            try{
                uni.setStorageSync('age', '18')
            }catch(e){
                console.log(e)
            }
        },
        onShow() {
            console.log('index onshow')
        },
        onHide() {
            console.log('index onhide')
        },
        methods: {
            asyncremove: function(){
                uni.removeStorage({
                    key: 'age',
                    success: function (res) {
                        console.log('async remove success');
                    }
                })
            },
            syncremove: function(){
                try{
                    uni.removeStorageSync('name');
                    console.log('sync remove success');
                }catch(e){
                    console.log(e);
                }
            }
        }
    }
</script>

<style>

</style>

显示: uni-app入门教程(5)接口的基本使用

此时可以删除指定的数据。

uni.getStorageInfo(OBJECT)uni.getStorageInfoSync()用于异步和同步获取当前 storage 的相关信息,uni.clearStorage()uni.clearStorageSync()用于异步和同步清理本地数据缓存,它们的用法与前3组接口类似。

总结

uni-app提供的的js接口包括标准ECMAScript的js API 和 uni 扩展 API 两部分,每个接口都能实现特定的功能,可以根据具体需要选择使用,来进一步加快开发效率。

本文原文首发来自https://blog.csdn.net/CUFEECR,可点击https://blog.csdn.net/CUFEECR/article/details/111579924查看。

点赞
收藏
评论区
推荐文章

暂无数据