@huodeming/wx_uni_request

1.0.0 • Public • Published

安装

npm install @huodeming/wx_uni_request

导入

// 按需导入 $http 对象
import { $http } from '@huodeming/wx_uni_request'

// 如果是在微信小程序项目中:将按需导入的 $http 挂载到 wx 顶级对象之上,方便全局调用
wx.$http = $http

// 如果是在 uni-app 项目中,可以把 $http 挂载到 uni 顶级对象之上,方便全局调用
uni.$http = $http

使用

支持的请求方法

// 发起 GET 请求,data 是可选的参数对象
$http.get(url, data?)

// 发起 POST 请求,data 是可选的参数对象
$http.post(url, data?)

// 发起 PUT 请求,data 是可选的参数对象
$http.put(url, data?)

// 发起 DELETE 请求,data 是可选的参数对象
$http.delete(url, data?)

配置请求根路径

$http.baseUrl = 'https://www.xitnds.com'

请求拦截器

// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
  // do somethimg...
}

例 1,展示 loading 效果:

// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
  wx.showLoading({
    title: '数据加载中...',
  })
}

例 2,自定义 header 请求头:

// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
  if (options.url.indexOf('/home/catitems') !== -1) {
    options.header = {
      'X-Test': 'AAA',
    }
  }
}

响应拦截器

// 请求完成之后做一些事情
$http.afterRequest = function (res) {
  // 做你想做的事情
  // 最后记得返回处理后的res,例: return res.data
  return res
}

例如,隐藏 loading 效果:

// 请求完成之后做一些事情
$http.afterRequest = function (res) {
  wx.hideLoading()
  return res
}

开源协议

MIT

enjoy!

Package Sidebar

Install

npm i @huodeming/wx_uni_request

Weekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

4.46 kB

Total Files

3

Last publish

Collaborators

  • huodeming