美文网首页小程序杂章程序员
微信小程序 wx.request 封装

微信小程序 wx.request 封装

作者: 鲸I落 | 来源:发表于2018-09-03 18:15 被阅读2318次

    配置域名

    一般情况下,项目中的域名前缀都是配置在 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()...

    感谢浏览微信小程序 wx.request 封装,欢迎评论指正,转载请标明出处

    相关文章

      网友评论

        本文标题:微信小程序 wx.request 封装

        本文链接:https://www.haomeiwen.com/subject/xysiwftx.html