微信小程序request封装

收藏


// request.js
function request(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: options.header || {},
      success: resolve,
      fail: reject
    })
  })
}
function put(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url,
      method: 'PUT',
      data: options.data || {},
      header: options.header || {},
      success: resolve,
      fail: reject
    })
  })
}
function del(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url,
      method: 'DELETE',
      data: options.data || {},
      header: options.header || {},
      success: resolve,
      fail: reject
    })
  })
}
function post(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url,
      method: 'POST',
      data: options.data || {},
      header: options.header || {},
      success: resolve,
      fail: reject
    })
  })
}
function checkStatus(response) {
  const { statusCode, data } = response
  if (statusCode >= 200 && statusCode < 300) {
    return Promise.resolve(data)
  } else {
    const error = new Error(`请求失败,状态码:${statusCode}`)
    error.response = response
    throw error
  }
}
function interceptor(chain) {
  const requestInterceptor = (options) => {
    options.header.Authorization = 'Bearer' + getApp().globalData.token
    return chain.request(options)
  }
  const responseInterceptor = (response) => {
    const { statusCode, data } = response
    if (statusCode >= 200 && statusCode < 300) {
      getApp().globalData.userInfo = data.userInfo
    } else {
      const error = new Error(`请求失败,状态码:${statusCode}`)
      error.response = response
      throw error
    }
    return response
  }
  return {
    request: requestInterceptor,
    response: responseInterceptor
  }
}
export { request, put, del, post, checkStatus, interceptor }
import { request, interceptor, checkStatus } from './request'
const chain = interceptor({
  request: (options) => {
    console.log('请求拦截器')
    return options
  },
  response: (response) => {
    console.log('响应拦截器')
    return response
  }
})
request({
  url: 'https://xxx.com/api/users',
  method: 'GET'
})
  .then(checkStatus)
  .then(data => {
 return console.log(data)
  })
  .catch(error => {
   console.log(error)
  })

5.注意事项

① 在使用拦截器时,需要注意拦截器的执行顺序。在上述示例中,拦截器的执行顺序是先执行请求拦截器,再执行响应拦截器。

② 在小程序中,我们可以使用getApp()函数来获取小程序实例,从而访问全局变量。

③ 在发送请求时,需要注意请求的参数配置。在上述示例中,默认使用的是GET请求方法和空对象作为请求参数,并且配置了常用请求方式,如果需要使用其他请求方法或者自定义请求参数,请在调用request函数时进行相应的配置。

实际上请求的url地址也可以单独封装的,需要单独新建一个js文件里面导出域名或者url地址,再调用request封装的地方,import引入一下就可以了,以上便是关于小程序封装网络请求和拦截器的全部内容

评论(

您还未登录,请先去登录
表情
查看更多

相关作者

  • 获取点赞0
  • 文章阅读量264

相关文章

联系小鹿线

咨询老师

咨询老师

扫码下载APP