uni-ajax

website·Indexed 31 days ago

https://uniajax.ponjs.com

A lightweight, Promise-based network request library for uni-app. It features request instances, interceptors for handling requests and responses, and configuration options consistent with uni.request. Supports TypeScript for improved development experience and static analysis.

Tokens
8K
Snippets
48
Records
52
Agent score
56%

What's inside uni-ajax

  1. Overview of uni-ajax for uni-app

    uni-ajax is a lightweight, Promise-based network request library for uni-app. It wraps the default uni.request method using a pattern similar to Axios, making it more flexible and suitable for enterprise development while remaining lightweight. It is compatible with TypeScript and supports request/response interception, custom request instances, multiple HTTP methods, and RequestTask operations.
  2. Implement silent Token refreshing

    To refresh an expired token without user interruption, use a response interceptor to detect the expiration code (e.g., 401). When detected, trigger a token refresh process and queue subsequent requests until the new token is acquired, then retry the original request.
    // refresh.js
    import request from './ajax'
    
    let isRefreshing = false
    let requestQueue = []
    
    const executeQueue = error => {
      requestQueue.forEach(promise => {
        error ? promise.reject(error) : promise.resolve()
      })
      requestQueue = []
    }
    
    const getToken = () => request.post('/oauth/token')
    
    const refreshToken = () => {
      if (isRefreshing) {
        return new Promise((resolve, reject) => {
          requestQueue.push({ resolve, reject })
        })
      }
    
      isRefreshing = true
      return new Promise((resolve, reject) => {
        getToken()
          .then(res => (res.data.code === 200 ? res : Promise.reject(res)))
          .then(res => {
            uni.setStorageSync('TOKEN', res.data.data)
            resolve()
            executeQueue(null)
          })
          .catch(err => {
            uni.removeStorageSync('TOKEN')
            reject(err)
            executeQueue(err || new Error('Refresh token error'))
          })
          .finally(() => {
            isRefreshing = false
          })
      })
    }
    
    export default refreshToken
    
    // ajax.js
    import ajax from 'uni-ajax'
    import refreshToken from './refresh'
    
    const instance = ajax.create({
      baseURL: 'https://www.example.com/api'
    })
    
    instance.interceptors.request.use(config => {
      config.header['Authorization'] = uni.getStorageSync('TOKEN')
      return config
    })
    
    instance.interceptors.response.use(
      response => {
        if (response.data.code === 401) {
          return refreshToken().then(() => instance(response.config))
        }
        return response
      },
      error => Promise.reject(error)
    )
    
    export default instance
  3. Create a custom request instance

    Use ajax.create() to create a request instance with specific settings. The configuration can be a static object, a function that returns a config object, or an asynchronous function returning a Promise of a config object.
    // Static configuration
    const instance = ajax.create({
      baseURL: 'https://www.example.com/api'
    })
    
    // Dynamic configuration via function
    const instanceFunc = ajax.create(() => ({
      baseURL: 'https://www.example.com/api'
    }))
  4. Set up uni-ajax with TypeScript

    To use TypeScript with uni-ajax, projects must be created using the CLI scaffolding rather than directly through HBuilderX. The recommended workflow involves creating a dedicated ajax instance and exporting it for use across the application.
    import ajax from 'uni-ajax'
    
    const instance = ajax.create()
    
    export default instance
  5. Create a request instance with uni-ajax

    Use ajax.create(config) to create a request instance. This is useful for defining a common base URL and applying shared interceptors across multiple API calls to avoid code redundancy.
    import ajax from 'uni-ajax'
    
    // Create instance
    const instance = ajax.create({
      // Initial instance configuration
    })
    
    export default instance
  6. Implement response interceptors in uniajax

    Response interceptors process the server's response before it reaches the .then() or .catch() blocks. By default, responses with HTTP status codes in the range [200, 300) trigger the success handler. You can return response.data directly to simplify the data received in the final .then() call, or return Promise.reject() to force the flow into the .catch() block based on custom business logic (e.g., checking a status code in the response body).
    // Basic response interceptor
    instance.interceptors.response.use(
      response => {
        return response
      },
      error => {
        return Promise.reject(error)
      }
    )
    
    // Example: Extracting data directly and handling business errors
    instance.interceptors.response.use(response => {
      if (response.data.code !== 1) {
        uni.showToast({ title: response.data.msg, icon: 'none' })
        return Promise.reject(response) // Trigger .catch()
      }
      return response.data // Return only the data payload to .then()
    })
  7. Install uni-ajax via npm, yarn, or pnpm

    For professional project development, installing via a package manager is recommended. After installation, import the library directly from the package name.
    # Using npm
    npm install uni-ajax
    
    # Using yarn
    yarn add uni-ajax
    
    # Using pnpm
    pnpm add uni-ajax
    import ajax from 'uni-ajax'
  8. Initiate a request using uni-ajax

    The main ajax export (or a created instance) is a function used to initiate requests. It supports three primary invocation patterns: passing a configuration object, passing positional arguments (URL, data, config), or using a configuration object with callback functions (success/fail).
    import ajax from 'uni-ajax'
    
    // 1. Using a config object (Promise-based)
    ajax({
      url: 'https://www.example.com/api/demo',
      data: { value: 'ajax' },
      header: { token: 'c275bdb5be55e7c2' }
    }).then(res => console.log(res))
    
    // 2. Using positional arguments [url, data, config] (Promise-based)
    ajax(
      'https://www.example.com/api/demo',
      { value: 'ajax' },
      { header: { token: 'c275bdb5be55e7c2' } }
    ).then(res => console.log(res))
    
    // 3. Using a config object with callbacks (v2.5.0+)
    ajax({
      url: 'https://www.example.com/api/demo',
      data: { value: 'ajax' },
      success: res => {
        console.log(res)
      }
    })
  9. Implement request and response interceptors

    Interceptors allow you to process requests before they are sent and responses before they are handled by the application. Use interceptors.request.use and interceptors.response.use to add handlers. To trigger a failure/catch event, the error handler must return Promise.reject.
    // Request Interceptor
    ajax.interceptors.request.use(
      config => {
        // Modify config before request
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    
    // Response Interceptor
    ajax.interceptors.response.use(
      response => {
        // Process response data
        return response
      },
      error => {
        return Promise.reject(error)
      }
    )
  10. Implement request interceptors in uniajax

    Request interceptors allow you to process or modify the configuration object before a request is sent. The interceptor receives a config object which is a merge of the request-specific config, instance config, and global config. To abort a request and trigger the .catch() block, return Promise.reject().
    // Basic request interceptor
    instance.interceptors.request.use(
      config => {
        // Modify config before request
        return config
      },
      error => {
        // Handle request errors
        return Promise.reject(error)
      }
    )
    
    // Example: Adding an Authorization token from storage
    instance.interceptors.request.use(config => {
      const token = uni.getStorageSync('TOKEN')
      if (token) {
        config.header['Authorization'] = token
      }
      return config
    })
    
    // Example: Aborting a request
    instance.interceptors.request.use(config => {
      return Promise.reject({
        config,
        errMsg: 'request:fail intercepted'
      })
    })
  11. Pass custom data to interceptors

    Any property added to the request configuration object that is not a recognized uni-ajax key will be passed through to the request and response interceptors.
    // Request
    ajax({
      url: 'https://www.example.com/api/demo',
      customData: 'hello'
    })
    
    // Request Interceptor
    ajax.interceptors.request.use(config => {
      console.log(config.customData) // 'hello'
      config.sharedValue = 'world'
      return config
    })
    
    // Response Interceptor
    ajax.interceptors.response.use(response => {
      console.log(response.config.customData) // 'hello'
      console.log(response.config.sharedValue) // 'world'
      return response
    })
    
  12. Initiate requests using uni-ajax

    Requests can be initiated by calling the imported package directly or by using a created request instance. The request function returns a Promise and supports two primary parameter signatures. Method aliases like .get(), .post(), .put(), and .delete() are also provided; when using these aliases, the method property in the config object is ignored.
    import ajax from 'uni-ajax'
    
    // Option 1: Using the imported package
    ajax()
    
    // Option 2: Using a created instance
    const instance = ajax.create()
    instance()
    
    // Signature A: Single config object
    ajax(config)
    
    // Signature B: URL, data, and config
    ajax(url, data, config)
    
    // Using method aliases
    ajax.get('/api/user')
    ajax.post('/api/user', { name: 'test' })