阿里云主机折上折
  • 微信号
Current Site:Index > Network requests and data storage in mini-programs

Network requests and data storage in mini-programs

Author:Chuan Chen 阅读数:54867人阅读 分类: 微信小程序

WeChat Mini Programs, as a lightweight application form, provide rich APIs and solutions for network requests and data storage. Developers can use wx.request to interact with servers while managing data through local storage, databases, or caching mechanisms to meet the needs of various scenarios.

Basic Usage of Network Requests

WeChat Mini Programs provide the wx.request method for initiating HTTP requests. This method supports multiple request types such as GET and POST and can handle response data in formats like JSON and XML. Below is a simple example of a GET request:

wx.request({
  url: 'https://api.example.com/data',
  method: 'GET',
  success(res) {
    console.log('Request succeeded', res.data)
  },
  fail(err) {
    console.error('Request failed', err)
  },
  complete() {
    console.log('Request completed')
  }
})

In actual development, wx.request is often encapsulated to handle errors uniformly, add request headers, etc. For example:

const request = (options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      header: {
        'Content-Type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      success(res) {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: reject
    })
  })
}

Concurrency and Limitations of Requests

Mini Programs impose certain restrictions on network requests. Developers should note the following:

  1. The number of concurrent requests initiated by a single Mini Program cannot exceed 10.
  2. The request URL must be included in the list of valid domains configured in the Mini Program admin console.
  3. The default timeout is 60 seconds, which can be adjusted using the timeout parameter.

For scenarios requiring multiple concurrent requests, Promise.all can be used:

Promise.all([
  request({ url: 'https://api.example.com/users' }),
  request({ url: 'https://api.example.com/products' })
]).then(([users, products]) => {
  console.log(users, products)
}).catch(err => {
  console.error(err)
})

Data Caching Mechanisms

Mini Programs offer two primary data storage methods: local storage and caching.

Local Storage

wx.setStorage and wx.getStorage provide simple key-value storage, suitable for small amounts of data like user preferences:

// Synchronous method
wx.setStorageSync('key', 'value')
const value = wx.getStorageSync('key')

// Asynchronous method
wx.setStorage({
  key: 'key',
  data: 'value',
  success() {
    wx.getStorage({
      key: 'key',
      success(res) {
        console.log(res.data)
      }
    })
  }
})

Limitations of local storage:

  • A single key cannot exceed 1MB.
  • Total storage cannot exceed 10MB.
  • Data persists unless the user manually deletes the Mini Program.

Caching System

For caching network resources, wx.downloadFile and wx.saveFile can be used:

wx.downloadFile({
  url: 'https://example.com/image.jpg',
  success(res) {
    wx.saveFile({
      tempFilePath: res.tempFilePath,
      success(savedRes) {
        console.log('File saved at', savedRes.savedFilePath)
      }
    })
  }
})

Database Storage

For scenarios requiring complex queries and large-scale data storage, Mini Programs offer cloud development databases and local databases.

Cloud Development Database

The cloud development database is a Serverless solution that eliminates the need for self-hosted servers:

const db = wx.cloud.database()
db.collection('todos').add({
  data: {
    description: 'Learn Mini Program development',
    done: false
  },
  success(res) {
    console.log('Added successfully', res._id)
  }
})

Local Database

Mini Programs also support local data storage using SQLite, though additional configuration is required:

const db = wx.getSystemInfoSync().SDKVersion >= '2.7.0' ? 
  wx.getOpenDatabase({
    name: 'mydb',
    version: '1.0',
    size: 5 * 1024 * 1024
  }) : null

if (db) {
  db.transaction(tx => {
    tx.executeSql(
      'CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY, text TEXT)'
    )
  })
}

Data Security and Optimization

In actual development, data security and performance optimization are critical considerations:

  1. Sensitive data should avoid local storage and instead use server storage.
  2. For large datasets, consider pagination and lazy loading.
  3. Use data encryption to protect user privacy.
  4. Implement data synchronization mechanisms for offline scenarios.
// Data encryption example
const crypto = require('crypto')

function encryptData(data, key) {
  const cipher = crypto.createCipher('aes-256-cbc', key)
  let encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex')
  encrypted += cipher.final('hex')
  return encrypted
}

function decryptData(encrypted, key) {
  const decipher = crypto.createDecipher('aes-256-cbc', key)
  let decrypted = decipher.update(encrypted, 'hex', 'utf8')
  decrypted += decipher.final('utf8')
  return JSON.parse(decrypted)
}

Practical Application Scenarios

Take a news Mini Program as an example to demonstrate the combined use of network requests and data storage:

  1. Fetch the news list from the server on initial load.
  2. Cache the news list locally.
  3. When a user clicks on a news item, first check if the full content is available locally.
  4. Display cached news when offline.
  5. Synchronize the latest data when online.
// Fetch news list
function fetchNewsList() {
  return request({ url: 'https://api.example.com/news' }).then(data => {
    wx.setStorageSync('news_list', data)
    return data
  }).catch(() => {
    return wx.getStorageSync('news_list') || []
  })
}

// Fetch single news detail
function fetchNewsDetail(id) {
  const cached = wx.getStorageSync(`news_${id}`)
  if (cached) {
    return Promise.resolve(cached)
  }
  return request({ url: `https://api.example.com/news/${id}` }).then(data => {
    wx.setStorageSync(`news_${id}`, data)
    return data
  })
}

Performance Monitoring and Debugging

Mini Programs provide various tools to monitor the performance of network requests and data storage:

  1. Use wx.reportAnalytics to report key metrics.
  2. Analyze requests via the Network panel in the Mini Program developer tools.
  3. Inspect local storage data using the Storage panel.
  4. Implement a custom performance logging system.
// Performance monitoring example
const perf = {
  start: {},
  mark(name) {
    this.start[name] = Date.now()
  },
  measure(name) {
    const duration = Date.now() - this.start[name]
    wx.reportAnalytics('performance', {
      name,
      duration
    })
    return duration
  }
}

// Usage example
perf.mark('news_request')
fetchNewsList().then(() => {
  const duration = perf.measure('news_request')
  console.log(`Request took: ${duration}ms`)
})

Cross-Platform Compatibility

When adapting Mini Programs to different platforms, special handling may be required for network requests and data storage:

  1. Alipay Mini Programs use my.request instead of wx.request.
  2. Baidu Mini Programs use swan.request.
  3. Toutiao Mini Programs use tt.request.
  4. Use conditional compilation or an adaptation layer to handle differences.
// Cross-platform adaptation example
function platformRequest(options) {
  if (typeof wx !== 'undefined') {
    return wx.request(options)
  } else if (typeof my !== 'undefined') {
    return my.request(options)
  } else if (typeof swan !== 'undefined') {
    return swan.request(options)
  }
  throw new Error('Unsupported platform')
}

Advanced Features and Future Trends

As the Mini Program ecosystem evolves, advanced features in network requests and data storage have emerged:

  1. WebSocket long connections support real-time data updates.
  2. Cloud functions provide more flexible server-side logic.
  3. Incremental updates reduce data transfer volume.
  4. Preloading strategies enhance user experience.
// WebSocket example
const socket = wx.connectSocket({
  url: 'wss://example.com/ws'
})

socket.onOpen(() => {
  console.log('Connection established')
  socket.send({
    data: JSON.stringify({ type: 'subscribe', topic: 'news' })
  })
})

socket.onMessage((res) => {
  console.log('Received message', res.data)
})

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.