(1)在api/index.js文件中創(chuàng)建ReqClient
const API_HOST = 'https://xxx.xxx.com' //接口前綴
const ReqClient = (url, method, data) => {
return new Promise((resolve, reject) => {
wx.showLoading();
if (method === 'GET') {
var header = {
'content-type': "application/x-www-form-urlencoded"
}
} else if (method === 'POST') {
var header = {
'content-type': 'application/json'
}
}
wx.request({
url: API_HOST + url,
data,
method,
header: header,
timeout: 6000,
success: (res) => {
wx.hideLoading();
if (res.statusCode === 500) {
wx.showModal({
title: '提示',
content: '網(wǎng)絡(luò)服務(wù)異常啦逆!',
showCancel: false
})
reject(res);
} else if (res.statusCode === 200) {
if (res.data.code === 200) {
resolve(res);
} else {
//業(yè)務(wù)處理
reject(res);
}
} else {
wx.showModal({
title: '錯誤信息',
content: '操作失敗薇芝!如需幫助請聯(lián)系技術(shù)人員',
showCancel: false
})
}
},
fail: (err) => {
wx.hideLoading();
wx.showModal({
title: '錯誤信息',
content: '網(wǎng)絡(luò)不可用泉唁,請檢查你的網(wǎng)絡(luò)狀態(tài)或稍后再試挣郭!',
showCancel: false
})
reject(err);
}
})
})
}
(2)在api/user.js文件中使用ReqClient聲明請求(也可以和第一步放在同一個文件中)
import {
ReqClient
} from './index'
//檢查用戶登錄狀態(tài)
export const checkLoginStatus = (data) => {
return ReqClient('/wx/auth/status', 'POST', {
...data
})
}
(3)在業(yè)務(wù)代碼中引入checkLoginStatus,就可以直接使用啦
import {
checkLoginStatus
} from '../../api/user';
進階
為什么可以使用 es6 的 import 去引用 commonjs 規(guī)范定義的模塊,或者反過來也可以又是為什么钟沛?
答案:https://www.cnblogs.com/jiaoshou/p/15988575.html