微信小程序怎么封装网络请求和拦截器

其他教程   发布日期:2024年10月28日   浏览次数:375

这篇文章主要介绍“微信小程序怎么封装网络请求和拦截器”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“微信小程序怎么封装网络请求和拦截器”文章能帮助大家解决问题。

    1. 前言

    今天和合作伙伴对接代码的时候,打开压缩包,发现项目有很大的问题,项目里根本没有登录验证请求封装拦截器这些东西,在开发小程序时,无疑想要维护还是比较麻烦的,实际上我们通常需要封装网络请求和拦截器,以实现统一处理状态码和存储用户登录信息等功能。这样可以提高开发效率,减少代码重复,同时也可以提高代码的可维护性和可读性。

    2. 思路

    封装网络请求

    首先,需要封装网络请求,负责发送请求和处理响应。该类应该包含以下方法:

    ·request(url, method, data, header):发送网络请求,并返回响应结果。

    ·get(url, data, header):发送 GET 请求。

    ·post(url, data, header):发送 POST 请求。

    等不同请求方式

    可以使用小程序提供的 wx.request 方法来实现网络请求,该方法的参数与上述方法的参数一一对应。在处理响应时,可以使用Promise对象来处理异步操作。

    统一处理状态码

    可以创建一个

    1. checkStatus
    函数,用于统一处理状态码。该函数接受一个response参数,用于判断请求是否成功。如果请求成功,则返回一个
    1. Promise
    对象,以便于我们进行后续的操作。如果请求失败,则抛出一个错误。

    创建 拦截器类

    具体处理逻辑见下文。

    2.1 封装网络请求

    封装一个request函数,用于发送请求。该函数接受一个参数options,用于配置请求。我们可以在该函数中使用小程序提供的

    1. wx.request
    接口发送请求,并在请求完成后返回一个Promise对象,以便于我们进行后续的操作。
    1. function request(options) {
    2. return new Promise((resolve, reject) => {
    3. wx.request({
    4. url: options.url,
    5. method: options.method || 'GET',
    6. data: options.data || {},
    7. header: options.header || {},
    8. success: resolve,
    9. fail: reject
    10. })
    11. })
    12. }

    2.2 统一处理状态码

    我们可以封装一个

    1. checkStatus
    函数,用于统一处理状态码。该函数接受一个response参数,用于判断请求是否成功。如果请求成功,则返回一个
    1. Promise
    对象,以便于我们进行后续的操作。如果请求失败,则抛出一个错误。
    1. function checkStatus(response) {
    2. const { statusCode, data } = response
    3. if (statusCode >= 200 && statusCode < 300) {
    4. return Promise.resolve(data)
    5. } else {
    6. const error = new Error(`请求失败,状态码:${statusCode}`)
    7. error.response = response
    8. throw error
    9. }
    10. }

    2.3 封装拦截器

    我们可以封装一个

    1. interceptor
    函数,用于封装拦截器。该函数接受一个chain参数,用于执行拦截器链。我们可以在该函数中定义一个
    1. requestInterceptor
    和一个
    1. responseInterceptor
    ,用于分别处理请求和响应的拦截器。我们可以在
    1. requestInterceptor
    中设置请求头,以便于在后续的请求中进行身份验证。我们可以在
    1. responseInterceptor
    中统一处理状态码,并在请求成功时更新用户登录信息。
    1. function interceptor(chain) {
    2. const requestInterceptor = (options) => {
    3. // 设置请求头
    4. options.header.Authorization = 'Bearer ' + getApp().globalData.token
    5. return chain.request(options)
    6. }
    7. const responseInterceptor = (response) => {
    8. const { statusCode, data } = response
    9. if (statusCode >= 200 && statusCode < 300) {
    10. // 更新用户登录信息
    11. getApp().globalData.userInfo = data.userInfo
    12. } else {
    13. const error = new Error(`请求失败,状态码:${statusCode}`)
    14. error.response = response
    15. throw error
    16. }
    17. return response
    18. }
    19. return {
    20. request: requestInterceptor,
    21. response: responseInterceptor
    22. }
    23. }

    2.4不同请求方式兼容

    1. //封装put请求方式的代码如下:
    2. function put(options) {
    3. return new Promise((resolve, reject) => {
    4. wx.request({
    5. url: options.url,
    6. method: 'PUT',
    7. data: options.data || {},
    8. header: options.header || {},
    9. success: resolve,
    10. fail: reject
    11. })
    12. })
    13. }
    14. //封装delete请求方式的代码如下:
    15. function del(options) {
    16. return new Promise((resolve, reject) => {
    17. wx.request({
    18. url: options.url,
    19. method: 'DELETE',
    20. data: options.data || {},
    21. header: options.header || {},
    22. success: resolve,
    23. fail: reject
    24. })
    25. })
    26. }
    27. //封装post请求方式的代码如下:
    28. function post(options) {
    29. return new Promise((resolve, reject) => {
    30. wx.request({
    31. url: options.url,
    32. method: 'POST',
    33. data: options.data || {},
    34. header: options.header || {},
    35. success: resolve,
    36. fail: reject
    37. })
    38. })
    39. }

    2.5 全局存储用户登录信息

    我们可以在小程序的app.js中定义一个全局变量

    1. globalData
    ,用于存储用户登录信息。我们可以在登录成功后将用户信息保存到该变量中,并在后续的请求中使用该变量进行身份验证。
    1. App({
    2. globalData: {
    3. userInfo: null,
    4. token: null
    5. }
    6. })

    2.6 完整代码

    1. // request.js
    2. function request(options) {
    3. return new Promise((resolve, reject) => {
    4. wx.request({
    5. url: options.url,
    6. method: options.method || 'GET',
    7. data: options.data || {},
    8. header: options.header || {},
    9. success: resolve,
    10. fail: reject
    11. })
    12. })
    13. }
    14. function put(options) {
    15. return new Promise((resolve, reject) => {
    16. wx.request({
    17. url: options.url,
    18. method: 'PUT',
    19. data: options.data || {},
    20. header: options.header || {},
    21. success: resolve,
    22. fail: reject
    23. })
    24. })
    25. }
    26. function del(options) {
    27. return new Promise((resolve, reject) => {
    28. wx.request({
    29. url: options.url,
    30. method: 'DELETE',
    31. data: options.data || {},
    32. header: options.header || {},
    33. success: resolve,
    34. fail: reject
    35. })
    36. })
    37. }
    38. function post(options) {
    39. return new Promise((resolve, reject) => {
    40. wx.request({
    41. url: options.url,
    42. method: 'POST',
    43. data: options.data || {},
    44. header: options.header || {},
    45. success: resolve,
    46. fail: reject
    47. })
    48. })
    49. }
    50. function checkStatus(response) {
    51. const { statusCode, data } = response
    52. if (statusCode >= 200 && statusCode < 300) {
    53. return Promise.resolve(data)
    54. } else {
    55. const error = new Error(`请求失败,状态码:${statusCode}`)
    56. error.response = response
    57. throw error
    58. }
    59. }
    60. function interceptor(chain) {
    61. const requestInterceptor = (options) => {
    62. options.header.Authorization = 'Bearer ' + getApp().globalData.token
    63. return chain.request(options)
    64. }
    65. const responseInterceptor = (response) => {
    66. const { statusCode, data } = response
    67. if (statusCode >= 200 && statusCode < 300) {
    68. getApp().globalData.userInfo = data.userInfo
    69. } else {
    70. const error = new Error(`请求失败,状态码:${statusCode}`)
    71. error.response = response
    72. throw error
    73. }
    74. return response
    75. }
    76. return {
    77. request: requestInterceptor,
    78. response: responseInterceptor
    79. }
    80. }
    81. export { request, put, del, post, checkStatus, interceptor }

    3. 使用示例

    1. import { request, interceptor, checkStatus } from './request'
    2. const chain = interceptor({
    3. request: (options) => {
    4. console.log('请求拦截器')
    5. return options
    6. },
    7. response: (response) => {
    8. console.log('响应拦截器')
    9. return response
    10. }
    11. })
    12. request({
    13. url: 'https://xxx.com/api/users',
    14. method: 'GET'
    15. })
    16. .then(checkStatus)
    17. .then(data => {
    18. console.log(data)
    19. })
    20. .catch(error => {
    21. console.log(error)
    22. })

    4. 注意事项

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

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

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

    以上就是微信小程序怎么封装网络请求和拦截器的详细内容,更多关于微信小程序怎么封装网络请求和拦截器的资料请关注九品源码其它相关文章!