zoukankan      html  css  js  c++  java
  • 小程序 使用Promise封装request 接口请求

    //httpService.js
    const host = 'https://baidu.com/ceshi' // 接口请求的域名 // get请求使用 json对象转字符串 (formatParams ) const formatParams = (data) => { let arr = [] for (let name in data) { arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name])) } return arr.join('&') } // 创建统一调用函数 const httpService = (url, params, method, loading = true) => { wx.showLoading({ title: '数据加载中...', }) let header = { "content-type": "application/json;charset=UTF-8" } return new Promise((resolve, reject) => { if (method === 'post') { wx.request({ url: host + url, data: params, method: method, header: header, timeout: 15000, complete: (res) => { resolve(res) wx.hideLoading() } }) } else if (method === 'get'){ wx.request({ url: host + url + '?' + formatParams(params), method: method, header: header, timeout: 15000, complete: (res) => { resolve(res) wx.hideLoading() } }) } }) }
    module.exports = {
      httpService
    }
    
    
    //api.js 定义使用的接口api 实现统一管理
    const { httpService } = require('httpService.js') /** * @name 医生/患者-我的提问详情页 * @param {*} params */ const questionSessionId = (sessionId, params) => { return httpService(`question/${sessionId}`, params, 'get') } module.exports = { questionSessionId }

    页面使用

    const { questionSessionId } = require('../../utils/api.js') // 引用
    // 使用 方法一
     questionSessionId(id, data).then(res=>{
          console.log(res)
        }).catch(res=>{
          console.log(res)
        }
     )
    // 使用方法二
    async questionSession() {
          const getData= await questionSessionId(id, data)
          console.log(getData)
    }     
  • 相关阅读:
    杀死JS错误提示
    年月日时分秒加星期即时显示的JS日期时间特效
    用JS自动缩小超出大小的图片
    实现简单的FAQ折叠效果
    复制本贴地址传给QQ/MSN好友的代码
    java初学者笔记总结day1
    java初学者笔记总结day2
    java初学者笔记总结day3
    IIS7.5应用程序池集成模式和经典模式的区别介绍
    div模拟textarea文本域轻松实现高度自适应
  • 原文地址:https://www.cnblogs.com/wukongz/p/13578207.html
Copyright © 2011-2022 走看看