request.js
class service {
? constructor(options) {
? ? let header = {}
? ? if(!options.header){
? ? ? if(options.method === 'GET'){
? ? ? ? header['content-type'] = 'application/json'
? ? ? }else{
? ? ? ? header['content-type'] = 'application/x-www-form-urlencoded'
? ? ? }
? ? }else{
? ? ? header = options.header
? ? }
? ? if(options.hasToken){
? ? ? header['token'] = wx.getStorageSync('token')
? ? }
? ? ajaxTimes++;
? ? // 顯示加載中 效果
? ? wx.showLoading({
? ? ? title: "加載中",
? ? ? mask: true
? ? });
? ? // 定義公共的url
? ? const baseUrl="http://192.168.2.***:8888";
? ? return new Promise((resolve,reject)=>{
? ? ? wx.request({
? ? ? header:header,
? ? ? method: options.method,
? ? ? url:baseUrl+options.url,
? ? ? data: options.params,
? ? ? success:(result)=>{
? ? ? ? resolve(result.data);
? ? ? },
? ? ? fail:(err)=>{
? ? ? ? reject(err);
? ? ? },
? ? ? complete:()=>{
? ? ? ? ajaxTimes--;
? ? ? ? if(ajaxTimes===0){
? ? ? ? ? //? 關(guān)閉正在等待的圖標(biāo)
? ? ? ? ? wx.hideLoading();
? ? ? ? }
? ? ? }
? ? ? });
? ? })
? }
}
api.js
import service from '../utils/request'
const getToken = (params) => {
? return new service({
? ? url: '/htohcloud-admin/login',
? ? method: 'POST',
? ? hasToken: false,
? ? header: {
? ? ? 'content-type': 'application/json'
? ? },
? ? params
? })
}
export default {
? getToken
}
使用
import api from '../../api/api'
const params = {
? ? username: '',
? ? password: ''
}
api.getToken(params).then(res => {
? ? ? if(res.code === 0){
? ? ? ? wx.setStorageSync('token', res.data.token)
? ? ? }else{
? ? ? ? wx.showToast({
? ? ? ? ? title: res.msg,
? ? ? ? })
? ? ? }
? ? })