距離做完項目很久了,騰出點時間,記錄下。爲了提高效率與可維護性,對其進行了一個簡單的封裝~
一、目錄結構
二、三步驟
1、第一層封裝(config.js)
分別針對get與post進行一個公共wx.request請求的封裝;每個方法傳了2個參數,url與data;
url:接口地址,
data:請求的參數,
const commonUrl ="https://ceshi.com/up/" //公共路徑
// post請求封裝
function postRequest(url, data) {
var promise = new Promise((resolve, reject) => {
var that = this;
var postData = data;
uni.request({
url: commonUrl + url,
data: postData,
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded',
'token': uni.getStorageSync("token")
},
success: function(res) {
// 此處的code=0,只是個舉例,有的可能是1等其他的,具體的看後臺決定,
//返回什麼就相應的做調整
if (res.statusCode == 200 && res.data.code == 0) {
resolve(res.data.data);
} else {
// 請求服務器成功,但是由於服務器沒有數據返回,此時無code。會導致這個空數據
//接口後面的then執行
// 不下去,導致報錯,所以還是要resolve下,這樣起碼有個返回值,
//不會被阻斷在那裏執行不下去!
resolve(res.data.data);
}
},
error: function(e) {
reject('網絡出錯');
}
})
});
return promise;
}
// get請求封裝
function getRequest(url, data) {
var promise = new Promise((resolve, reject) => {
var that = this;
var postData = data;
uni.request({
url: commonUrl + url,
data: postData,
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function(res) {
if (res.statusCode == 200 && res.data.code == 0) {
resolve(res.data.data);
} else {
resolve(res.data.data);
}
},
error: function(e) {
reject('網絡出錯');
}
})
});
return promise;
}
module.exports = {
postRequest,
getRequest
}
2、第二層封裝(http.js)
在http.js文件中進行第二層封裝,即進行每個具體功能接口的請求封裝;
這一層傳請求的接口地址url
var config = require('./config.js')
// 文章請求列表
var getArticleList = function(e){
return config.getRequest("article/list",e);
}
module.exports = {
getArticleList
}
3、調用、傳參(index.js)
在index.js中調用http.js中的接口;
這一層傳請求的參數data
<template>
<view>每日一讀</view>
</template>
<script>
import http from '../../utils/http.js';
export default{
onLoad() {
http.getArticleList().then(list=>{
console.log(list)
// 此處的list就是config.js中,wx.request封裝中resolve的值,
//即list===res.data.data的值;
})
// 如果需要向服務器傳值,可以這樣寫
http.getArticleList({
open:"value"
}).then(list=>{
console.log(list)
})
}
}
</script>
封裝形式多種多樣,這裏只是其中一種,比如有的封裝了一層,調用的時候url與參數data一起傳,但不建議這樣,後續修改的話要去每個頁面改。雖然地址不會經常改,但還是建議最好進行二層封裝,把地址放在同一個文件好管理,僅供參考~