swan.request

    Object object

    使用缓存服务时 success 返回参数说明

    参数类型说明
    errnoString缓存服务返回,非 “0” 表示失败
    errmsgString缓存服务返回,”succ” 或者错误提示信息
    logidString缓存服务返回,缓存服务的日志 ID
    dataString开发者服务器返回的数据,其中 data 为开发者服务 HTTP.Response.Body 进行 base64 编码后的数据
    headerObject开发者服务器返回的 HTTP Response Header
    statusCodeNumber开发者服务器返回的 HTTP 状态码
    • 返回示例如下:

    • JSON

    未使用缓存服务时 success 返回参数说明

    使用缓存服务时 fail 返回参数说明

    参数类型说明
    errnoString缓存服务返回,非 “0” 表示失败
    errmsgString缓存服务返回,”succ” 或者错误提示信息
    logidString缓存服务返回,缓存服务的日志 ID
    • 缓存服务错误码说明
    • 返回示例如下:

    • JSON

    1. "errno":"400000",
    2. "errmsg":"invaild input",
    3. "logid":"352381125"
    4. }

    未使用缓存服务时 fail 返回参数说明

    • Android
    错误码说明
    201解析失败,请检查调起协议是否合法
    1001执行失败
    • iOS

    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)…)。

    扫码体验

    代码示例

    请使用百度APP扫码

    图片示例

    swan.request - 图2

    代码示例 1:使用了云端缓存服务能力

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <view class="wrap">
    2. <view class="card-area">
    3. <view class="top-description border-bottom">点击向服务器发起请求</view>
    4. <button bind:tap="request" type="primary" loading="{{loading}}" hover-stop-propagation="true">button</button>
    5. <view class="tip-week">将项目信息里的校验域名取消勾选可访问 ip 测试</view>
    6. </view>
    7. </view>
    1. Page({
    2. data: {
    3. loading: false
    4. },
    5. request() {
    6. this.setData('loading', true);
    7. swan.request({
    8. url: 'https://storage.smartapps.cn/shopping/nianhuo/bimai',
    9. header: {
    10. 'Content-Type': 'application/json',
    11. 'Developer-Server-Domain': 'https://sfc.baidu.com',
    12. 'X-SP-Accept-Encoding': 'base64',
    13. 'X-SP-Transfer-Encoding': '1'
    14. },
    15. method: 'POST',
    16. dataType: 'json',
    17. responseType: 'text',
    18. data: {
    19. tabname: '美食酒水'
    20. },
    21. success: res => {
    22. try {
    23. console.log('request success', res);
    24. swan.showModal({
    25. title: '请求到的数据',
    26. content: JSON.stringify(res.data),
    27. showCancel: false
    28. });
    29. }
    30. catch (error) {
    31. console.log(error);
    32. }
    33. },
    34. fail: err => {
    35. swan.showToast({
    36. title: JSON.stringify(err)
    37. });
    38. console.log('request fail', err);
    39. },
    40. complete: () => {
    41. this.setData('loading', false);
    42. }
    43. });
    44. }
    45. });

    在开发者工具中打开

    • SWAN
    • JS
    • REQUEST.JS
    1. <view class="wrap">
    2. <view class="card-area">
    3. <view class="tip-strong">
    4. 开发者接入使用此能力需要在开发者管理平台(https://smartprogram.baidu.com/developer/applist.html)配置开关后,按照 js 中标注引入
    5. </view>
    6. <view class="top-description border-bottom">点击向服务器发起请求</view>
    7. <button bind:tap="request" type="primary" loading="{{loading}}" hover-stop-propagation="true">button</button>
    8. <view class="tip-week">将项目信息里的校验域名取消勾选可访问 ip 测试</view>
    9. </view>
    10. </view>
    1. /**
    2. * 开发者原有的业务文件
    3. */
    4. // 1、添加 util 文件里的 request.js,并在此引入
    5. let util = require('../util/request.js');
    6. Page({
    7. data: {
    8. loading: false
    9. },
    10. request() {
    11. // 2、将 swan.request 替换为 swan.requestStorage1,注:此处应防止 API 重名问题,注意设为唯一标识
    12. swan.requestStorage1 = util.requestStorage;
    13. swan.requestStorage1({
    14. // swan.request({
    15. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    16. data: {
    17. tabname: '美食酒水'
    18. },
    19. header: {
    20. 'Content-Type': 'application/json'
    21. },
    22. method: 'POST',
    23. dataType: 'JSON',
    24. responseType: 'text',
    25. success: res => {
    26. this.setData('loading', true);
    27. swan.showModal({
    28. title: 'success',
    29. content: JSON.stringify(JSON.parse(res.data).data)
    30. });
    31. console.log('request success', JSON.parse(res.data).data);
    32. },
    33. fail: err => {
    34. swan.showToast({
    35. title: JSON.stringify(err)
    36. });
    37. console.log('request fail', err);
    38. },
    39. complete: () => {
    40. this.setData('loading', false);
    41. console.log('request complete');
    42. }
    43. });
    44. }
    45. });
    1. /**
    2. * 云端缓存 request 封装
    3. */
    4. function requestStorage({url, header, success, fail, complete, ...param}) {
    5. const {oldHost, newHost} = parseUrl(url);
    6. // header 字段的添加
    7. const newHeader = Object.assign(header, {
    8. 'Developer-Server-Domain': oldHost,
    9. 'X-SP-Accept-Encoding': 'base64',
    10. 'X-SP-Transfer-Encoding': '1'
    11. });
    12. swan.request({
    13. url: newHost,
    14. header: newHeader,
    15. success: function (res) {
    16. // server失败的话,会把statusCode设置为非200,这个时候走原开发者服务
    17. try {
    18. if (res.statusCode !== 200) {
    19. throw new Error('server 缓存返回非正常http状态码:' + res.statusCode);
    20. }
    21. }
    22. catch (error) {
    23. console.log(error);
    24. swan.request({url, header, success, fail, complete, ...param});
    25. }
    26. },
    27. fail: function (err) {
    28. console.log('server 缓存返回失败,走原有 request 请求,错误信息为:', err);
    29. swan.request({url, header, success, fail, complete, ...param});
    30. },
    31. complete: function () {
    32. if (typeof complete === "function") {
    33. complete();
    34. }
    35. },
    36. ...param});
    37. // 开发者域名的切割,切割规则可以根据开发者实际业务场景修改和完善,此处仅为示例
    38. function parseUrl(url) {
    39. let urlArr = url.split('/');
    40. let oldHost = urlArr[0] + '//' + urlArr[2];
    41. let newHost = url.replace(/\/\/(.*?)\//, '//storage.smartapps.cn/');
    42. return {
    43. oldHost,
    44. newHost
    45. };
    46. }
    47. module.exports.requestStorage = requestStorage;

    代码示例 3:post 的 header[‘content-type’] 为 application/json

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <view class="wrap">
    2. <view class="card-area">
    3. <view class="top-description border-bottom">点击向服务器发起请求</view>
    4. <button bind:tap="request" type="primary" loading="{{loading}}" hover-stop-propagation="true">请求</button>
    5. <view class="tip-week">将项目信息里的校验域名取消勾选可访问 ip 测试</view>
    6. </view>
    7. </view>
    1. Page({
    2. data: {
    3. loading: false
    4. },
    5. request() {
    6. this.setData('loading', true);
    7. swan.request({
    8. // 仅为示例,并非真实的接口地址
    9. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    10. data: {
    11. tabname: '美食酒水'
    12. },
    13. header: {
    14. 'Content-Type': 'application/json'
    15. },
    16. method: 'POST',
    17. dataType: 'JSON',
    18. responseType: 'text',
    19. success: res => {
    20. console.log('request success', res);
    21. swan.showModal({
    22. title: '请求到的数据',
    23. content: JSON.stringify(JSON.parse(res.data).data),
    24. showCancel: false
    25. });
    26. },
    27. fail: err => {
    28. swan.showToast({
    29. title: JSON.stringify(err)
    30. });
    31. console.log('request fail', err);
    32. },
    33. complete: () => {
    34. this.setData('loading', false);
    35. }
    36. });
    37. }
    38. });

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

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>

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

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>
    1. Page({
    2. request() {
    3. let cuid = '';
    4. swan.request({
    5. // 仅为示例,并非真实的接口地址
    6. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    7. header: {
    8. 'Content-Type': 'application/x-www-form-urlencoded',
    9. 'cookie': 'BAIDUCUID=' + cuid
    10. },
    11. method: 'POST',
    12. dataType: 'json',
    13. responseType: 'text',
    14. data: {
    15. key: 'value'
    16. },
    17. success: res => {
    18. console.log(res.data);
    19. },
    20. fail: err => {
    21. console.log('错误码:' + err.errCode);
    22. console.log('错误信息:' + err.errMsg);
    23. }
    24. });
    25. }
    26. });

    代码示例 6:post 的 dataType 为 string

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>
    1. Page({
    2. request() {
    3. swan.request({
    4. // 仅为示例,并非真实的接口地址
    5. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    6. header: {
    7. 'Content-Type': 'application/json'
    8. },
    9. method: 'POST',
    10. dataType: 'string',
    11. responseType: 'text',
    12. data: {
    13. key: 'value'
    14. },
    15. success: res => {
    16. console.log(res.data);
    17. },
    18. fail: err => {
    19. console.log('错误码:' + err.errCode);
    20. console.log('错误信息:' + err.errMsg);
    21. }
    22. });
    23. }
    24. });

    代码示例 7:post 的 data 为 string

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>
    1. Page({
    2. data: {
    3. loading: false
    4. },
    5. request() {
    6. this.setData('loading', true);
    7. swan.request({
    8. // 仅为示例,并非真实的接口地址
    9. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    10. header: {
    11. 'Content-Type': 'application/json'
    12. },
    13. method: 'POST',
    14. dataType: 'json',
    15. responseType: 'text',
    16. data: '美食酒水',
    17. success: res => {
    18. console.log('request success', res);
    19. swan.showModal({
    20. title: '请求到的数据',
    21. content: JSON.stringify(res.data.data),
    22. showCancel: false
    23. });
    24. },
    25. fail: err => {
    26. swan.showToast({
    27. title: JSON.stringify(err)
    28. });
    29. console.log('request fail', err);
    30. },
    31. complete: () => {
    32. this.setData('loading', false);
    33. }
    34. });
    35. });

    代码示例 8:post 的 responseType 为 arraybuffer

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>
    1. Page({
    2. request() {
    3. swan.request({
    4. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    5. header: {
    6. 'Content-Type': 'application/json'
    7. },
    8. method: 'POST',
    9. // 一般会将返回数据转化为BASE64编码格式
    10. dataType: 'json',
    11. responseType: 'arraybuffer',
    12. data: {
    13. key: 'value'
    14. },
    15. success: res => {
    16. console.log(res.data);
    17. },
    18. fail: err => {
    19. console.log('错误码:' + err.errCode);
    20. console.log('错误信息:' + err.errMsg);
    21. }
    22. });
    23. }
    24. });

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>

    代码示例 10:post 的 method 为 PUT

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>
    1. Page({
    2. request() {
    3. swan.request({
    4. // 仅为示例,并非真实的接口地址
    5. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    6. header: {
    7. 'Content-Type': 'application/json'
    8. },
    9. method: 'PUT',
    10. dataType: 'json',
    11. responseType: 'text',
    12. data: {
    13. key: 'value'
    14. },
    15. success: res => {
    16. console.log(res.data);
    17. },
    18. fail: err => {
    19. console.log('错误码:' + err.errCode);
    20. console.log('错误信息:' + err.errMsg);
    21. }
    22. });
    23. }
    24. });

    代码示例 11:post 的 method 为 DELETE

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>
    1. Page({
    2. request() {
    3. swan.request({
    4. // 仅为示例,并非真实的接口地址
    5. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    6. header: {
    7. 'Content-Type': 'application/json'
    8. },
    9. method: 'DELETE',
    10. dataType: 'json',
    11. responseType: 'text',
    12. data: {
    13. key: 'value'
    14. },
    15. success: res => {
    16. console.log(res.data);
    17. },
    18. fail: err => {
    19. console.log('错误码:' + err.errCode);
    20. console.log('错误信息:' + err.errMsg);
    21. }
    22. });
    23. }
    24. });

    代码示例 12:post 的 method 为 HEAD

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>
    1. Page({
    2. request() {
    3. swan.request({
    4. // 仅为示例,并非真实的接口地址
    5. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    6. header: {
    7. 'Content-Type': 'application/json'
    8. },
    9. method: 'HEAD',
    10. dataType: 'json',
    11. responseType: 'text',
    12. data: {
    13. key: 'value'
    14. },
    15. success: res => {
    16. console.log(res.data);
    17. },
    18. fail: err => {
    19. console.log('错误码:' + err.errCode);
    20. console.log('错误信息:' + err.errMsg);
    21. }
    22. });
    23. }
    24. });

    代码示例 13:post 的 method 为 OPTIONS

    在开发者工具中打开

    在 WEB IDE 中打开

    • SWAN
    • JS
    1. <button bindtap="request">点击请求数据</button>
    1. Page({
    2. request() {
    3. swan.request({
    4. // 仅为示例,并非真实的接口地址
    5. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    6. header: {
    7. 'Content-Type': 'application/json'
    8. },
    9. method: 'OPTIONS',
    10. dataType: 'json',
    11. responseType: 'text',
    12. data: {
    13. key: 'value'
    14. },
    15. success: res => {
    16. console.log(res.data);
    17. },
    18. fail: err => {
    19. console.log('错误码:' + err.errCode);
    20. console.log('错误信息:' + err.errMsg);
    21. }
    22. });
    23. }
    24. });

    返回值 :

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

    代码示例 14:防止用户快速点击,多次请求(加锁)

    • JS
    1. let hasClick = false;
    2. Page({
    3. tap() {
    4. if (hasClick) {
    5. return;
    6. }
    7. hasClick = true;
    8. swan.showLoading();
    9. swan.request({
    10. // 仅为示例,并非真实的接口地址
    11. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    12. method: 'POST',
    13. header: {
    14. 'Content-Type':'application/json'
    15. },
    16. success: res => {
    17. console.log(res.data);
    18. },
    19. fail: err => {
    20. swan.showToast({ title: '系统错误' });
    21. },
    22. complete: () => {
    23. swan.hideLoading();
    24. hasClick = false;
    25. }
    26. })
    27. }

    代码示例 15:promise 写法保障 request 的请求顺序

    在开发者工具中打开

    • JS

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

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