WeChat applet request package (get, post, put, remove)

http.js

const app = getApp()
const request = (url, options) => {
    
    
   return new Promise((resolve, reject) => {
    
    
       wx.request({
    
    
           url: `${
      
      app.globalData.serviceUrl}${
      
      url}`,
           method: options.method,
           data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
           header: {
    
    
            Authorization:wx.getStorageSync('token'),
            villageId:wx.getStorageSync('villageId')
           },
           success(request) {
    
    
               if (request.data.code === 200) {
    
    	//请求成功
                   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 })
}
const remove = (url, options) => {
    
    
   return request(url, {
    
     method: 'DELETE', data: options })
}

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

use

import http from '../../../utils/http'	//引入http.js
http.get(`api地址`, {
    
    }).then(res => {
    
    

}).catch(err => {
    
    

})

Guess you like

Origin blog.csdn.net/eightNine1102/article/details/106503212