wxRequest.js
/**
*
* @param {string} url 路径
* @param {string} method 方法 'GET'或'POST'
* @param {object} data 参数 {a:b}
* @param {boolean} isToken 请求头里面是否添加token,false表示不添加token
*/
export default function wxRequest(url, method, data, isToken, _loading = false) {
return new Promise((resolve, reject) => {
if (_loading) {
wx.showLoading({
title: '加载中...',
mask: true,
})
}
wx.request({
url: url,
method: method || 'GET',
data: data || null,
header: (isToken || true) ? { "Content-Type": "application/json", "token": getApp().globalData.token || '', } : { 'content-type': 'application/json' },
success: (res) => {
const { code, data } = res.data;
//请求成功
if (code == 0) {
return resolve(data);
}
//请求失败
if (code == 1) {
return reject(data)
}
// 未登录
if (code == 401 || code == 4001) {
//跳转登录页面
}
},
fail: (err)=> { },
complete: ()=> {
if (_loading) {
wx.hideLoading();
}
}
})
})
}
api.js
const baseURL = "http://xxxx"
export default const Api = {
getToken: baseURL + '/api/getToken',
login: baseURL + '/api/login'
}
fetch.js
import Api from './api'
import wxRequest from './wxRequest'
export function fetchLogin(data){
return wxRequest(Api.login,'POST',data)
}
export function fetchLogin(data){
return wxRequest(Api.login,'POST',data)
}
调用方法
import { fetchLogin, fetchLogin} from "./fetch"
fetchLogin().then(res=>{})
或者不要fetch.js
import Api from './api'
import wxRequest from './wxRequest'
wxRequest(Api.login,'POST',data).then(res=>{})
不错。