小程序 使用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)
}     

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM