微信小程序的請(qǐng)求模板request (簡(jiǎn)單易懂)

首先,我們?cè)诟夸浵葎?chuàng)建一個(gè)request 文件夾

然后里面一共分為三個(gè)部分1 .request.js 2. api.js 3. fetch.js 那我們來(lái)一起看看里面的代碼

1 .request.js的代碼

function request(params) {
  // 封裝網(wǎng)絡(luò)請(qǐng)求的代碼
  return new Promise(function (resolve, reject) {
    wx.request({
      url: params.url,
      data: params.data || {},
      header: params.header || {},
      method: params.method || 'GET',
      dataType: 'json',
      success: function(res) {
        resolve(res.data)
      },
      fail: function(err) {
        wx.showToast({
          title: err || '請(qǐng)求錯(cuò)誤!',
        })
        reject(err)
      }
    })
  }) 
}
// nodejs common
module.exports = {
  requestApi: request
}
  1. api.js
var baseUrl = 'http://192.168.113.113:8637' //這里請(qǐng)輸入你自己的接口地址
// 測(cè)試的服務(wù)器
// var baseUrl = 'http://192.168.113.116:8637'
// 正式環(huán)境
// var baseUrl = 'http://www.mysite.com'

var homeApi = baseUrl + '/xm/home'  //接口地址+接口的接口API
var loginApi = baseUrl + '/wx/login'  //接口地址+接口的接口API

// 導(dǎo)出
module.exports = {
  homeApi: homeApi,
  loginApi: loginApi
}
  1. fetch.js
// 引入兩個(gè)文件
var api = require('./api.js')
var request = require('./requst.js')

// get請(qǐng)求的的模板
function getHome(params) {
  return request.requestApi({
    url: api.homeApi  // 文件名+ 接口
  })
}
// post請(qǐng)求的模板
function LoginFn(params) {
  return request.requestApi({
    url: api.loginApi,   // 文件名+ 接口
    data: params,  
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    method: 'POST'
  })
}

 // 導(dǎo)出
module.exports = {
  getHome: getHome,
  LoginFn: LoginFn
}

接下來(lái)我們就可以在需要引用的頁(yè)面直接引用了

const fetch = require('../../request/fetch')

然后我們就可以在頁(yè)面通過(guò) fetch .getHome() 調(diào)用

實(shí)例
// get
fetch.getHome({
      Page: 1,
      size: 10,
    }).then(res => {
      console.log(res);=
    })
// post
  fetch.LoginFn({
      username:'wx',
      pwd:'wx'
    }).then(res=>{
      console.log(res);
    })
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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