后浪云百度小程序教程:swan.request

  • swan.request
    • 方法参数
      • object 参数说明
      • 使用缓存服务时 success 返回参数说明
      • 未使用缓存服务时 success 返回参数说明
      • 使用缓存服务时 fail 返回参数说明
      • 未使用缓存服务时 fail 返回参数说明
    • 示例
      • 图片示例
      • 代码示例 1:使用了云端缓存服务能力
      • 代码示例 2:云端缓存服务能力接入开发者服务
      • 代码示例 3:post 的 header[‘content-type’] 为 application/json
      • 代码示例 4:post 的 header[‘content-type’] 为 application/x-www-form-urlencoded
      • 代码示例 5:post 的 header 中携带 cookie
      • 代码示例 6:post 的 dataType 为 string
      • 代码示例 7:post 的 data 为 string
      • 代码示例 8:post 的 responseType 为 arraybuffer
      • 代码示例 9:post 的 method 为 GET
      • 代码示例 10:post 的 method 为 PUT
      • 代码示例 11:post 的 method 为 DELETE
      • 代码示例 12:post 的 method 为 HEAD
      • 代码示例 13:post 的 method 为 OPTIONS
      • 代码示例 14:防止用户快速点击,多次请求(加锁)
      • 代码示例 15:promise 写法保障 request 的请求顺序
    • 常见问题
      • Q:request 请求在 iOS 端会进入 fail 回调函数的原因有哪些?

    swan.request

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

    方法参数

    Object object

    object 参数说明

    属性名类型必填默认值说明最低支持版本Web 态说明
    urlString1、开发者服务域名 + path + query(未开启云端缓存服务能力)
    2、缓存服务域名 + path + query (开启云端缓存服务能力),其中缓存服务域名为:https://storage.smartapps.cn ,请求先转发到缓存服务,缓存服务未命中后,再转发到开发者服务
    dataObject/String请求的参数
    headerObject设置请求的 header:header 中不能设置 Referer ;若开启缓存服务,需要设置 Developer-Server-Domain ,该 key 存储开发者服务器的域名地址
    methodStringGET (大写)开启云端缓存服务能力的有效值:HEAD、GET、POST ;
    未开启云端缓存服务能力的有效值:OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE/CONNECT(仅 Android 支持)
    有效值:HEAD、GET、POST、PUT、DELETE
    dataTypeStringjson有效值:string、json、jsonp 。如果设为 json ,会尝试对返回的数据做一次 JSON.parse有效值:string、json、jsonp 。如果设为 jsonp ,客户端会发送如: https://sfc.baidu.com/shopping/nianhuo/bimai?SwanWebCallback=SwanWebCallback1599623580951_6 的请求,服务端返回数据时需要将 SwanWebCallback 参数的值作为函数名来包裹住 JSON 数据
    responseTypeStringtext设置响应的数据类型,有效值:text、arraybuffer1.11.20
    successFunction收到开发者服务成功返回的回调函数
    failFunction接口调用失败的回调函数
    completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

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

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

    • JSON

     
     
     
    1. {
    2. "errno":"0",
    3. "errmsg":"succ",
    4. "logid":"64295237",
    5. "data":"eyJkYXRhIjp7ImFwcF9saXN0IjpbeyJuYW1lIjoi6L+Z5piv5LiA5Liq5byA5Y+R6ICFc2VydmVy6L+U5Zue56S65L6LIn1dfSwiZXJybXNnIjoic3VjYyIsImVycm5vIjoiMCIsInJlcXVlc3RfaWQiOiIxMDI4MDkxODIiLCJ0aXBtc2ciOiIifQ==",
    6. "header":{
    7. "Content-Type":[
    8. "text/html"
    9. ],
    10. "Date":[
    11. "Thu, 10 Sep 2020 13:01:04 GMT"
    12. ],
    13. "P3p":[
    14. "CP=" OTI DSP COR IVA OUR IND COM "",
    15. "CP=" OTI DSP COR IVA OUR IND COM ""
    16. ],
    17. "Server":[
    18. "Apache"
    19. ],
    20. "Tracecode":[
    21. "00644508330215533322091021",
    22. "00644508330915916554091021"
    23. ],
    24. "Vary":[
    25. "Accept-Encoding"
    26. ]
    27. }
    28. }

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

    参数类型说明
    dataObject/String开发者服务器返回的数据
    statusCodeNumber开发者服务器返回的 HTTP 状态码
    headerObject开发者服务器返回的 HTTP Response Header

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

    参数类型说明
    errnoString缓存服务返回,非 “0” 表示失败
    errmsgString缓存服务返回,”succ” 或者错误提示信息
    logidString缓存服务返回,缓存服务的日志 ID
    • 缓存服务错误码说明
    错误码说明
    400000使用缓存服务,输入不合法
    400001使用缓存服务,请求传入的开发者域名 Developer-Server-Domain 不合法
    400002请求 Header 缺少 Referer 字段
    400003请求 Header 的 Referer 中小程序 app_key 错误
    400004请求 Header 缺少 Developer-Server-Domain 字段
    400005小程序可以访问的开发者域名列表为空
    400006小程序请求的域名不在开发者在开发者平台配置的 Domains 域名列表内
    500100云端缓存服务内部错误
    500101云端缓存服务访问内部下游模块失败
    502000使用缓存服务,开发者服务失败
    • 返回示例如下:

    • JSON

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

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

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

    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扫码

    图片示例

    代码示例 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. });

    代码示例 2:云端缓存服务能力接入开发者服务

    在开发者工具中打开

    在开发者工具中打开

    在 WEB IDE 中打开

    • 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. success(res);
    22. }
    23. catch (error) {
    24. console.log(error);
    25. swan.request({url, header, success, fail, complete, ...param});
    26. }
    27. },
    28. fail: function (err) {
    29. console.log('server 缓存返回失败,走原有 request 请求,错误信息为:', err);
    30. swan.request({url, header, success, fail, complete, ...param});
    31. },
    32. complete: function () {
    33. if (typeof complete === "function") {
    34. complete();
    35. }
    36. },
    37. ...param});
    38. }
    39. // 开发者域名的切割,切割规则可以根据开发者实际业务场景修改和完善,此处仅为示例
    40. function parseUrl(url) {
    41. let urlArr = url.split('/');
    42. let oldHost = urlArr[0] + '//' + urlArr[2];
    43. let newHost = url.replace(/\/\/(.*?)\//, '//storage.smartapps.cn/');
    44. return {
    45. oldHost,
    46. newHost
    47. };
    48. }
    49. 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>
     
     
     
    1. Page({
    2. request() {
    3. swan.request({
    4. // 仅为示例,并非真实的接口地址
    5. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    6. header: {
    7. 'Content-Type': 'application/x-www-form-urlencoded'
    8. },
    9. method: 'POST',
    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. });

    代码示例 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. }
    36. });

    代码示例 8:post 的 responseType 为 arraybuffer

    在开发者工具中打开

    在开发者工具中打开

    在 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. // 一般会将返回数据转化为BASE64编码格式
    11. dataType: 'json',
    12. responseType: 'arraybuffer',
    13. data: {
    14. key: 'value'
    15. },
    16. success: res => {
    17. console.log(res.data);
    18. },
    19. fail: err => {
    20. console.log('错误码:' + err.errCode);
    21. console.log('错误信息:' + err.errMsg);
    22. }
    23. });
    24. }
    25. });

    代码示例 9:post 的 method 为 GET

    在开发者工具中打开

    在开发者工具中打开

    在 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. method: 'GET',
    7. success: res => {
    8. console.log('request success', res);
    9. swan.showModal({
    10. title: '请求到的数据',
    11. content: JSON.stringify(res),
    12. showCancel: false
    13. });
    14. },
    15. fail: err => {
    16. swan.showToast({
    17. title: JSON.stringify(err)
    18. });
    19. console.log('request fail', err);
    20. },
    21. complete: () => {
    22. this.setData('loading', false);
    23. }
    24. });
    25. }
    26. });

    代码示例 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. }
    28. })

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

    在开发者工具中打开

    在开发者工具中打开

    在 WEB IDE 中打开

    • JS
     
     
     
    1. Page({
    2. onLoad() {
    3. this.requestTask = new Promise((resolve, reject) => {
    4. const requestHandler = swan.request({
    5. url: 'https://sfc.baidu.com/shopping/nianhuo/bimai',
    6. header: {
    7. 'Content-Type': 'application/json'
    8. },
    9. method: 'POST',
    10. dataType: 'json',
    11. responseType: 'text',
    12. data: {
    13. key: 'value'
    14. },
    15. success: res => {
    16. this.setData('data', res.data);
    17. resolve();
    18. },
    19. fail: err => {
    20. console.log('错误码:' + err.errCode);
    21. console.log('错误信息:' + err.errMsg);
    22. }
    23. })
    24. });
    25. },
    26. onShow() {
    27. this.requestTask.then(requestData => {
    28. let res = this.getData('data');
    29. swan.setPageInfo({
    30. title: res.title,
    31. keywords: res.keywords,
    32. description: res.description,
    33. articleTitle: res.articleTitle,
    34. releaseDate: res.releaseDate,
    35. image: res.image,
    36. video: res.video,
    37. visit: res.visit,
    38. likes: '75',
    39. comments: '13',
    40. collects: '23',
    41. shares: '8',
    42. followers: '35',
    43. success: res => {
    44. console.log('setPageInfo success', res);
    45. },
    46. fail: err => {
    47. console.log('setPageInfo fail', err);
    48. }
    49. })
    50. })
    51. }
    52. });

    常见问题

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

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

    THE END