codecamp

百度智能小程序 发起网络请求

swan.request

解释:发起网络请求,请参考使用注意事项进行开发。

方法参数

Object object

object参数说明

属性名 类型 必填 默认值 说明 最低支持版本 Web 态说明

url

String

开发者服务器接口地址

data

Object/String

请求的参数

header

Object

设置请求的 header,header 中不能设置 Referer。

method

String

GET (大写)

有效值:OPTIONS、GET、HEAD、POST、PUT、DELETE、 TRACE/CONNECT(仅 Android 支持)。

有效值:HEAD、GET、POST、PUT、DELETE

dataType

String

json

有效值:string、json。 如果设为 json,会尝试对返回的数据做一次 JSON.parse 。

responseType

String

text

设置响应的数据类型, 有效值:text、arraybuffer。

1.11.20

success

Function

收到开发者服务成功返回的回调函数。

fail

Function

接口调用失败的回调函数。

complete

Function

接口调用结束的回调函数(调用成功、失败都会执行)。

success 返回参数说明

参数 类型 说明

data

Object/String

开发者服务器返回的数据

statusCode

Number

开发者服务器返回的 HTTP 状态码

header

Object

开发者服务器返回的 HTTP Response Header

fail 返回参数说明

  • Android
错误码 说明

201

解析失败,请检查调起协议是否合法  

1001

执行失败

  • iOS
错误码 说明

202

解析失败,请检查调起协议是否合法

errorCode 为 4

URL 无效

data 数据说明

最终发送给服务器的数据都是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:1、对于 GET 方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…);

2、对于 POST 方法且 header[‘content-type’] 为 application/json 的数据,会对数据进行 JSON 序列化;

3、对于 POST 方法且 header[‘content-type’] 为 application/x-www-form-urlencoded 的数据,会将数据转换成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)。

示例


图片示例



代码示例 1: post 的 header['content-type'] 为 application/json

在开发者工具中打开

<view class="wrap">
    <view class="card-area">
        <view class="top-description border-bottom">点击向服务器发起请求</view>
        <button bind:tap="request" type="primary" loading="{{loading}}" hover-stop-propagation="true">请求</button>
        <view class="tip-week">将项目信息里的校验域名取消勾选可访问ip测试</view>
    </view>
</view>
Page({
    data: {
        loading: false
    },
    request() {
        this.setData('loading', true);
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            data: {
                tabname: '美食酒水'
            },
            header: {
                'content-type': 'application/json'
            },
            method: 'POST',
            dataType: 'JSON',
            responseType: 'text',
            success: res => {
                console.log('request success', res);
                swan.showModal({
                    title: '请求到的数据',
                    content: JSON.stringify(JSON.parse(res.data).data),
                    showCancel: false
                });
            },
            fail: err => {
                swan.showToast({
                    title: JSON.stringify(err)
                });
                console.log('request fail', err);
            },
            complete: () => {
                this.setData('loading', false);
            }
        });
    }
});


代码示例 2: post 的 header['content-type'] 为 application/x-www-form-urlencoded

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            dataType: 'json',
            responseType: 'text',
            data: {
                key: 'value'
            },
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    }
});


代码示例 3: post 的 header 中携带 cookie

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        let cuid = '';
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                'cookie': 'BAIDUCUID=' + cuid
            },
            method: 'POST',
            dataType: 'json',
            responseType: 'text',
            data: {
                key: 'value'
            },
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    }
});


代码示例 4: post 的 dataType 为 string

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/json'
            },
            method: 'POST',
            dataType: 'string',
            responseType: 'text',
            data: {
                key: 'value'
            },
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    }
});


代码示例 5: post 的 data 为 string

在开发者工具中打开

<button bindtap="request">点击请求数据</button>
Page({
    data: {
        loading: false
    },
    request() {
        this.setData('loading', true);
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/json'
            },
            method: 'POST',
            dataType: 'json',
            responseType: 'text',
            data: '美食酒水',
            success: res => {
                console.log('request success', res);
                swan.showModal({
                    title: '请求到的数据',
                    content: JSON.stringify(res.data.data),
                    showCancel: false
                });
            },
            fail: err => {
                swan.showToast({
                    title: JSON.stringify(err)
                });
                console.log('request fail', err);
            },
            complete: () => {
                this.setData('loading', false);
            }
        });
    }
});


代码示例 6: post 的 responseType 为 arraybuffer

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/json'
            },
            method: 'POST',
            dataType: 'arraybuffer',// 一般会将返回数据转化为BASE64编码格式
            responseType: 'text',
            data: {
                key: 'value'
            },
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    }
});


代码示例 7: get 请求

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            method: 'GET', 
            success: res => {
                console.log('request success', res);
                swan.showModal({
                    title: '请求到的数据',
                    content: JSON.stringify(res),
                    showCancel: false
                });
            },
            fail: err => {
                swan.showToast({
                    title: JSON.stringify(err)
                });
                console.log('request fail', err);
            },
            complete: () => {
                this.setData('loading', false);
            }
        });
    }
});


代码示例 8: post 的 method 为 PUT

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/json'
            },
            method: 'PUT',
            dataType: 'json',
            responseType: 'text',
            data: {
                key: 'value'
            },
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    }
});


代码示例 9: post 的 method 为 DELETE

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/json'
            },
            method: 'DELETE',
            dataType: 'json',
            responseType: 'text',
            data: {
                key: 'value'
            },
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    }
});


代码示例 10: post 的 method 为 HEAD

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/json'
            },
            method: 'HEAD',
            dataType: 'json',
            responseType: 'text',
            data: {
                key: 'value'
            },
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    }
});


代码示例 11: post 的 method 为 OPTIONS

在开发者工具中打开

<button bindtap="request">点击请求数据</button>

Page({
    request() {
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            header: {
                'content-type': 'application/json'
            },
            method: 'OPTIONS',
            dataType: 'json',
            responseType: 'text',
            data: {
                key: 'value'
            },
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    }
});

返回值 :
返回一个 requestTask 对象,通过 requestTask,可中断请求任务。


参考示例

参考示例 1: 防止用户快速点击,多次请求(加锁)

let hasClick = false;

Page({
    tap() {
        if (hasClick) {
            return;
        }
        hasClick = true;
        swan.showLoading();
        swan.request({
            url: 'https://sfc.baidu.com/shopping/nianhuo/bimai', // 仅为示例,并非真实的接口地址
            method: 'POST',
            header: {'content-type':'application/json'},
            success: res => {
                console.log(res.data);
            },
            fail: err => {
                swan.showToast({ title: '系统错误' });
            },
            complete: () => {
                swan.hideLoading();
                hasClick = false;
            }
        })
    }
})


参考示例 2: promise 写法保障 request 的请求顺序 

在开发者工具中打开

Page({
    onLoad() {
        this.requestTask = new Promise((resolve, reject) => {
            const requestHandler = swan.request({
                url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
                header: {
                    'content-type': 'application/json'
                },
                method: 'POST',
                dataType: 'json',
                responseType: 'text',
                data: {
                    key: 'value'
                },
                success: res => {
                    this.setData('data', res.data);
                    resolve();
                },
                fail: err => {
                    console.log('错误码:' + err.errCode);
                    console.log('错误信息:' + err.errMsg);
                }
            })
        });
    },
    onShow() {
        this.requestTask.then(requestData => {
            let res = this.getData('data');
            swan.setPageInfo({
                title: res.title,
                keywords: res.keywords,
                description: res.description,
                articleTitle: res.articleTitle,
                releaseDate: res.releaseDate,
                image: res.image,
                video: res.video,
                visit: res.visit,
                likes: '75',
                comments: '13',
                collects: '23',
                shares: '8',
                followers: '35',
                success: res => {
                    console.log('setPageInfo success', res);
                },
                fail: err => {
                    console.log('setPageInfo fail', err);
                }
            })
        })
    }
});


常见问题

Q:request 请求在 iOS 端会进入 fail 回调函数的原因有哪些

A:请查看 url 中是否出现了中文,如需要使用中文字符,请对中文字符进行 encodeURIComponent。


百度智能小程序 使用注意事项
百度智能小程序 网络请求任务对象
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

百度智能小程序开发文档

百度智能小程序 组件

百度智能小程序 地图

百度智能小程序 画布

百度智能小程序 API

百度智能小程序 界面

百度智能小程序 关注小程序引导组件

百度智能小程序 自定义组件

百度智能小程序 媒体

百度智能小程序 设备

百度智能小程序 拨打电话

百度智能小程序 内存警报

百度智能小程序 手机联系人

百度智能小程序 用户截屏事件

百度智能小程序 第三方平台

百度智能小程序 开放接口

百度智能小程序 百度收银支付

百度智能小程序 分包预下载

百度智能小程序 数据分析

百度智能小程序 服务端

百度智能小程序 云开发

百度智能小程序 初始化

百度智能小程序 云函数

百度智能小程序 服务端初始化

百度智能小程序 服务器获取上下文

百度智能小程序 服务端云函数

百度智能小程序 开发教程

百度智能小程序 功能开发

百度智能小程序 基本原理

百度智能小程序 小程序自动化

百度智能小程序 视频教程

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }