微信小程序.request封装

193 阅读1分钟

配置域名

一般情况下,项目中的域名前缀都是配置在 app.js 中

App({   
    onLaunch: function() {   
    },  
    globalData: {       
        userInfo: null,       
        loginCode: null,       
        version: '1.0.0',       
        host: 'https://**',   
    }
})

封装 wx.request

在小程序目录下建立 api 文件夹,并在文件夹下创建 api.js 脚本。下面开始封装 wx.request

const app = getApp()
​const request = (url, options) => {   
    return new Promise((resolve, reject) => {       
        wx.request({           
            url: `${app.globalData.host}${url}`,           
            method: options.method,           
            data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
            header: {               
                'Content-Type': 'application/json; charset=UTF-8',               
                'x-token': 'x-token'  // 看自己是否需要           
            },           
            success(request) {               
                if (request.data.code === 2000) {                   
                    resolve(request.data)               
                } else {                   
                    reject(request.data)               
                }           
            },           
            fail(error) {               
                reject(error.data)           
            }       
        })   
    })
}
const get = (url, options = {}) => {   
    return request(url, { 
        method: 'GET', data: options 
    })
}
​const post = (url, options) => {   
    return request(url, { 
        method: 'POST', data: options 
    })
}
​const put = (url, options) => {   
    return request(url, { 
        method: 'PUT', data: options 
    })
}​
// 不能声明DELETE(关键字)
const remove = (url, options) => {   
    return request(url, { 
        method: 'DELETE', data: options 
    })
}
​module.exports = {   
    get,   
    post,
    put,   
    remove
}

管理 api 接口

项目中的 api 大部分都是可以复用的。为了后期方便维护管理,这个时候需要把 api 提出来。有多种方法,比如可以按模块建立相应的 js 脚本。如下:

const login = '/user/login' // 登录
​module.exports = {    
    login
}

使用封装过后的 api

import api from '../api/api'import { login } from '../**/conf' // 链接注意填写正确 ​
api.post(login, {    
    data: ''
}).then(res => {    
    if(){

    }
}).catch(err => {    
    wx.showToast({        
        title: err.message,        
        icon: 'none'    
    })
})

post 请求就是api.post()...,get 请求就是api.get()...

来自简书 鲸I落