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)
    }     
  • 相关阅读:
    使用阿里云ECS安装HDFS的小问题
    退役回忆录嘤嘤嘤
    2018 ICPC北京 H ac自动机
    Educational Codeforces Round 54 (Rated for Div. 2) DE
    sa learning
    网络流learning
    Python模块logging
    Python模块unittest
    Linux /dev/shm
    Shell 字符串操作
  • 原文地址:https://www.cnblogs.com/wukongz/p/13578207.html
Copyright © 2011-2022 走看看