小程序開發(fā)之一(使用fly進行http封裝)

原文鏈接

下載fly js文件

fly小程序文檔

/api/config.js

配置,主要配置全局的host url和request攔截和request攔截


var Fly=require("../lib/wx.js") //wx.js is your downloaded code
var fly=new Fly(); //Create an instance of Fly

// Add interceptors
fly.interceptors.request.use((config,promise)=>{
  wx.showLoading({
    title: '加載中',
    mask:true
  })
  // Add custom headers
  
  return config;
})
fly.interceptors.response.use(
  (response,promise) => {
    if(typeof (response.data)=='string' && response.data!=''){
      response.data=JSON.parse(response.data);
    }

    if(response.data.code=="C501"){
      
      
    }
    wx.hideLoading()

    // response.data=Mock.mock(response.data)
    // Do something with response data .
    // Just return the data field of response

  },
  (err,promise) => {
    // Do something with response error
    //promise.resolve("ssss")
    wx.hideLoading()
  }

)
// Set the base url
fly.config.baseURL="https:127.0.0.1"

export default fly;

生成對應(yīng)模塊api文件,比如user

//引入配置文件
import fly from './config'

export default {
  // 獲取我的的閱讀指導(dǎo)
  get:function (params) {
    return fly.get("/user",params);
  },
  delete:function (params) {
    return fly.delete("/user",params);
  },
}

/api/index.js

api入口文件,引入所有模塊的api,用的時候只需要因為index即可。

import fly from './config'
import book from './book'
import bookList from './book-list'
import classList from './class'
import rank from './rank'
import readPlan from './read-plan'
import user from './user'
import reaction from './reaction'
import task from './task'
import until from './until'
import guide from './guide'
import badge from './badge'
import activity from './activity'

let api= {
  book,
  bookList,
  classList,
  rank,
  readPlan,
  user,
  reaction,
  task,
  until,
  guide,
  badge,
  activity,
  apiHost:fly.config.baseURL//這屬性輸出當前http域名
}

export default api;

使用

建議直接在app中引入/api/index.js
然后其他頁面再使用同過app使用

xxx.api.user.get({userId:1}).then((res)=>{
     console.log(res);
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容