es6 封裝request請求
為了使代碼更精簡,便於理解和維護,使用 new Promise方法對request請求進行封裝
new Promise(resolve, reject) 含有兩個參數
resolve :成功時的調用
reject:失敗時的調用
app.js中封裝request請求
App({ onLaunch: function(options) { }, globalData: { localUrl: "https://www.baidu.com", }, request(api, params, method) { return new Promise((resolve, reject) => { wx.request({ url: this.globalData.localDoctorUrl + api, data: params, header: { 'content-type': 'application/x-www-form-urlencoded', 'csrf-csrf': 'csrf-csrf', }, method: method ? method : 'get', success: (res) => { resolve(res) }, fail: (err) => { wx.showToast({ title: err, icon: 'none' }); reject("請求失敗") } }) }) }, })
在其他需要用到請求的頁面直接引用
const app=getApp(); //request請求 app.request("接口地址","參數","post/get").then(res=>{ //請求成功的處理 }).catch(err=>{ //請求失敗的處理 })
======================================================================================================================================================
或者,直接引用request.js
const host = 'http://........'; function request(api, params, method, resolve, reject) { wx.request({ url: host + api, data: params, header: { "content-type": "application/json;charset=UTF-8", }, method: method ? method : 'get', success: function (res) { resolve(res); }, fail: function (err) { reject(err); }, }) } module.exports.request = request;
在index.js中使用
import { request } from '../../config/request.js'; //request路徑 const api = "/..........."; getRequest() { request(api, params, method, res => { console.log(res) //請求成功的操作 wx.showToast({ title: "請求成功", icon: 'success' }) }, err => { console.log(err) //請求失敗操作 wx.showToast({ title: '發表請求失敗', icon: 'none' }) }) }