Network requests and data storage in mini-programs
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:
- The number of concurrent requests initiated by a single Mini Program cannot exceed 10.
- The request URL must be included in the list of valid domains configured in the Mini Program admin console.
- 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:
- Sensitive data should avoid local storage and instead use server storage.
- For large datasets, consider pagination and lazy loading.
- Use data encryption to protect user privacy.
- 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:
- Fetch the news list from the server on initial load.
- Cache the news list locally.
- When a user clicks on a news item, first check if the full content is available locally.
- Display cached news when offline.
- 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:
- Use
wx.reportAnalytics
to report key metrics. - Analyze requests via the Network panel in the Mini Program developer tools.
- Inspect local storage data using the Storage panel.
- 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:
- Alipay Mini Programs use
my.request
instead ofwx.request
. - Baidu Mini Programs use
swan.request
. - Toutiao Mini Programs use
tt.request
. - 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:
- WebSocket long connections support real-time data updates.
- Cloud functions provide more flexible server-side logic.
- Incremental updates reduce data transfer volume.
- 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
上一篇:小程序的数据绑定与状态管理
下一篇:小程序的用户授权与登录机制