当前位置:网站首页>Wechat applet wx Request request encapsulation

Wechat applet wx Request request encapsulation

2022-06-26 12:27:00 C+ Ankou wood

The way 1:

// utils/wxAjax.js
const baseUrl = 'https://*****/';// Here, you can obtain different domain names through the environment variables 
//  Encapsulation request 
module.exports = function (options) {
    
  return new Promise((resolve, reject) => {
    
    wx.showLoading({
    
      title: ' Loading ',
    });
    wx.request({
    
      url: baseUrl + options.url,
      method:
        options.method === 'GET' ? options.data : JSON.stringify(options.data),
      data: options.data,
      header: {
    
        'content-type': 'application/json',
        // 'x-token': 'x-token'
      },
      success: function (res) {
    
        resolve(res);
        // Status judgment can be added here 
      },
      fail: function (error) {
    
        reject(error);
      },
      complete: () => {
    
        setTimeout(() => {
    
          wx.hideLoading();
        }, 100);
      },
    });
  });
};

Use :

 // Use on other pages  import request from '../utils/wxAjax'
 // Further encapsulation -1.js
 export const QUERY_USER_INFO=(data = {
     })=> {
    
        return request({
    
            // baseURL: hostConfig.xxx,
            url: "/api/user/info",
            method: "GET",
            data,
        });
    },
 // Use -2.js
 import {
     QUERY_USER_INFO } from 'xxx'
 
  QUERY_USER_INFO({
    a:1}).then(res => {
    
    if(){
    }
  }).catch(err => {
    
    wx.showToast({
    
        title: err.message,
    })
})

Mode two :

Create in applet directory api Folder , And create... In the folder api.js Script . Now start packaging 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',
           },
           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 })
}
//  Cannot declare DELETE( keyword )
const remove = (url, options) => {
    
   return request(url, {
     method: 'DELETE', data: options })
}

module.exports = {
    
   get,
   post,
   put,
   remove
}

Use encapsulated api

import api from '../api/api'

api.post('/api/user/info', {
    
    data: ''
}).then(res => {
    
    console.log(res)
}).catch(err => {
    
    wx.showToast({
    
        title: err.message,
    })
})

post The request is api.post()…,get The request is api.get()…

Mode three :

get Just send the request directly ,post request JSON.stringify(data) once

const baseURL = 'https://some-domain.com/api/';
let header = {
    'content-type': 'application/json'};

function request(method, url, data) {
    
    return new Promise(function(resolve, reject) {
    
        wx.request({
    
            url: baseURL + url,
            method: method,
            data: method === POST ? JSON.stringify(data) : data,
            header: header,
            success(res) {
    
                // The request is successful 
                // Judge status code ---errCode The status is determined according to the backend definition 
                if (res.data.errCode == 0) {
    
                    resolve(res);
                } else {
    
                    // Other anomalies 
                    reject(' Runtime error , Please try again later ');
                }
            },
            fail(err) {
    
                // request was aborted 
                reject(err)
            }
        })
    })
}

Use :
1, In a small program util New under folder api.js, And put the above code in and create the request , And export

// Import request after 
const API = {
    
    getOpenid: (data) => request(GET, `jsapi/mini?jsCode=${
      data}`),
};
module.exports = {
    
    API: API,
    // xxx,
}

2, Here we get openid Interface, for example
stay .js Introduce... Into the document api.js Under the API

const $api = require('../../utils/api.js').API;
Page({
    
    data: {
    },
    onLoad: function (options) {
    
        wx.login({
    
            success:res=> {
    
                //  Call interface get openid
                $api.getOpenid(res.code)
                    .then(res => {
    
                       // The request is successful 
                    })
                    .catch(err => {
    
                       // request was aborted 
                    })
            }
        })
    }
})
原网站

版权声明
本文为[C+ Ankou wood]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170516079504.html