当前位置:编程学习 > 微信小程序 >>

微信小程序request封装(get,post,put,remove)

微信小程序中进行网络请求的封装方法,通过使用Promise和wx.request实现GET、POST、PUT和DELETE等HTTP请求方式。文章详细展示了如何设置请求头、处理响应状态码及数据,并提供了具体代码实例。

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
}

使用

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

}).catch(err => {

})
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,