Home  >  Article  >  Web Front-end  >  How to encapsulate network request methods in the uniapp project

How to encapsulate network request methods in the uniapp project

PHPz
PHPzOriginal
2023-04-20 13:49:191340browse

With the advent of the mobile Internet era, APP has become an indispensable part of people’s lives. In order to provide better services and user experience, the use of network requests in APP has become an indispensable link. How to effectively encapsulate network requests and improve code reusability and maintainability has become an important topic. This article will introduce how to encapsulate the network request method in the uniapp project.

1. Network requests in uniapp

The uniapp framework is developed based on the Vue.js framework, so the network request method in uniapp is similar to Vue.js. To use network requests in uniapp, you need to use the uni.request method. The syntax is as follows:

uni.request({
    url: '',
    data: {},
    header: {},
    method: 'GET',
    dataType: 'json',
    responseType: 'text',
    success: res => {},
    fail: () => {},
    complete: () => {}
})

The meaning of its parameters is as follows:

  • url: Interface address
  • data: Request parameters, passed in key-value pairs
  • header: Request header parameters, passed in key-value pairs
  • method: Request method, supports GET, POST, PUT, DELETE, etc.
  • dataType: Data type, default is json
  • responseType: Response data type, default is text
  • success: Success callback function
  • fail: Failure callback function
  • complete: Request completion callback function

2. Network request method encapsulation

In actual development, in order to improve code reuse For safety and maintainability, we usually encapsulate the uni.request method. The following is an example of Promise-based network request method encapsulation:

function request(url, data, method = 'GET', header = {}) {
    return new Promise((resolve, reject) => {
        uni.request({
            url,
            data,
            method,
            header,
            success: res => {
                resolve(res.data)
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

Among them, we use the Promise object to encapsulate the uni.request method and return a Promise object , so that corresponding processing can be performed when the request succeeds or fails.

Next, we mount this network request method to the Vue.js instance so that it can be called throughout the project. Before mounting, we need to encapsulate the request method again and add some common parameters, such as interface prefix, request data type, etc. The sample code is as follows:

import Config from '@/config'

function request(url, data = {}, method = 'GET', header = {}) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: Config.baseUrl + url,
      data,
      method,
      dataType: 'json',
      header: {
        'Content-Type': 'application/json',
        ...header
      },
      success: res => {
        resolve(res.data)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

export default {
  install(Vue, options) {
    Vue.prototype.$http = {
      get: (url, data, header) => {
        return request(url, data, 'GET', header)
      },
      post: (url, data, header) => {
        return request(url, data, 'POST', header)
      },
      put: (url, data, header) => {
        return request(url, data, 'PUT', header)
      },
      delete: (url, data, header) => {
        return request(url, data, 'DELETE', header)
      }
    }
  }
}

In this example, we introduce a configuration file Config to store related information such as interface addresses. We also configured common request parameters, such as interface prefix, data type, etc. Finally, the network request method that implements common parameters and Promise is mounted on the Vue.js instance through Vue.prototype.$http.

3. Use of network request method

At this step, we have completed the encapsulation and mounting of the network request method in uniapp, and now it can be used freely in the project. The following is a simple usage example:

<template>
  <view>
    <button @tap="getData">获取数据</button>
    <view>{{ message }}</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      message: ''
    }
  },
  methods: {
    async getData() {
      try {
        const res = await this.$http.get('/api/data')
        console.log(res)
        this.message = res.message
      } catch (e) {
        console.error(e)
      }
    }
  }
}
</script>

In this example, we use async/await to process network requests asynchronously, simplifying code writing. At the same time, we can also see that we did not write the relevant code for network requests in each component, but directly called the $http request method mounted on the Vue.js instance to achieve Code reuse.

4. Summary

Through the introduction of this article, we can see that it is not difficult to encapsulate the network request method in uniapp. On the contrary, through simple code encapsulation and mounting, we can greatly improve the reusability and maintainability of the code, and at the same time avoid code redundancy to a certain extent. I hope this article will be helpful to you and allow you to better grasp the development of uniapp.

The above is the detailed content of How to encapsulate network request methods in the uniapp project. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn