• 封装小程序http请求


    (一) promise封装一个请求接口
    // 该文件为request.js
    const host = 'http://localhost:8088/aaa/' // 域名
    const request = (method, url, data, isLoading = true) => {
    	if (isLoading) {
    		wx.showLoading({
    			title: '加载中'
    		});
    	}
    	var promise = new Promise(function(resolve, reject) {
    		wx.request({
    			url: host + url,
    			data: data,
    			method: method,
    			header: {
    				"Content-Type": "application/json;charset=UTF-8",
    				//"userId":wx.getStorageSync('userId'),
    			},
    			success: function(res) {
    				if (isLoading) {
    					wx.hideLoading();
    				}
    				if (res.status) {
    					resolve(res.data);
    				} else {
    					layerTip('网络错误');
    				}
    			},
    			fail: function(res) {
    				// fail调用接口失败
    				wx.hideLoading();
    			}
    		})
    	});
    	return promise;
    }
    
    export request
    

    (二) 写一个公共的调用接口的文件globalData.js

    import {request} from './request'
     
    //请求登陆接口
    export const requestLogin = (loginName,password) => request('post','/api/doLogin',{loginName,password})
    

    (三) 页面调用接口

    // 局部引入需要的调用的接口
    import {requestLogin} from './globalData.js'
    
    // 对应的登录按钮方法里,调用接口,传入参数
    login () {
            requestLogin(this.loginName,this.password).then(res => {
                if (res.status) {
                        wx.showToast({
                        title: '登录成功',
                        icon: 'success',
                        duration: 2000
                    })
                }
           })
    }
    
  • 相关阅读:
    centos6.5-搭建LNMP
    mysql组织结构
    mysql主从复制
    centos6.5-搭建mysql5.7.9
    操作系统的历史
    用户&权限&系统
    awk是全局周期
    在vm上面安装Linux系统
    Linux rpm yum 等安装软件
    linux中execve函数的用法
  • 原文地址:https://www.cnblogs.com/linjiu0505/p/11820522.html
Copyright © 2020-2023  润新知