【愚公系列】《微信小程序开发解析》014-网络API
🏆 作者简介,愚公搬代码
🏆《头衔》:华为云特约编辑,华为云云享专家,华为开发者专家,华为产品云测专家,CSDN博客专家,CSDN商业化专家,阿里云专家博主,阿里云签约作者,腾讯云优秀博主,腾讯云内容共创官,掘金优秀博主,亚马逊技领云博主,51CTO博客专家等。
🏆《近期荣誉》:2022年度博客之星TOP2,2023年度博客之星TOP2,2022年华为云十佳博主,2023年华为云十佳博主等。
🏆《博客内容》:.NET、Java、Python、Go、Node、前端、IOS、Android、鸿蒙、Linux、物联网、网络安全、大数据、人工智能、U3D游戏、小程序等相关领域知识。
🏆🎉欢迎 👍点赞✍评论⭐收藏
🚀前言
在现代移动应用开发中,网络通信是至关重要的一环。微信小程序作为一种轻量级的应用形式,凭借其便捷的使用体验和丰富的功能,已经成为开发者和用户的热门选择。为了实现与服务器的数据交互,掌握微信小程序的网络API显得尤为重要。
本文将深入探讨微信小程序的网络API,帮助开发者了解如何高效地进行数据请求、处理响应以及管理网络状态。我们将详细讲解常用的网络API,包括 wx.request
、wx.uploadFile
和 wx.downloadFile
等,结合实际案例和使用场景,展示如何在小程序中实现数据的获取和交互。
无论您是刚入门的小程序开发者,还是希望提升网络编程能力的经验者,本篇文章都将为您提供实用的指导和深入的洞见。让我们一起学习微信小程序网络API,掌握实现高效数据交互的技巧,开启更丰富的开发旅程!
🚀一、网络API
🔎1.wx.request
微信小程序(WeChat Mini Programs)中的 wx.request
是用于向服务器发起网络请求的方法。
🦋1.1 wx.request
参数详解
wx.request
方法用于发起 HTTPS 网络请求,参数是一个对象。其属性如下:
-
url (string) - 必填
- 请求的 URL 地址。
-
data (object | string | ArrayBuffer)
- 请求的参数,可以是对象(推荐)、字符串或 ArrayBuffer。
-
header (object)
- 请求的头部信息,默认为
{'content-type': 'application/json'}
。
- 请求的头部信息,默认为
-
method (string)
- HTTP 请求方法,默认为
GET
。支持OPTIONS
,GET
,HEAD
,POST
,PUT
,DELETE
,TRACE
,CONNECT
。
- HTTP 请求方法,默认为
-
dataType (string)
- 返回的数据格式。默认为
json
,如果设置为其他
,会返回原始数据。
- 返回的数据格式。默认为
-
responseType (string)
- 响应的数据类型,可以是
text
或arraybuffer
。默认为text
。
- 响应的数据类型,可以是
-
success (function)
- 接口调用成功的回调函数,参数为返回的数据。
-
fail (function)
- 接口调用失败的回调函数。
-
complete (function)
- 接口调用结束的回调函数(无论成功或失败)。
🦋1.2 CRUD 封装使用案例
为了更方便地进行 CRUD 操作,可以将 wx.request
封装成一个通用的函数。
// request.js
const baseUrl = 'https://api.example.com'; // 替换为你的接口地址
const request = (url, method, data, header = { 'content-type': 'application/json' }) => {
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + url,
method: method,
data: data,
header: header,
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(res);
}
},
fail: (err) => {
reject(err);
}
});
});
};
const api = {
get: (url, data, header) => request(url, 'GET', data, header),
post: (url, data, header) => request(url, 'POST', data, header),
put: (url, data, header) => request(url, 'PUT', data, header),
delete: (url, data, header) => request(url, 'DELETE', data, header)
};
module.exports = api;
🦋1.3 使用封装的 CRUD 操作
假设我们有一个用户相关的 API,可以进行增删改查操作,下面是如何使用封装好的 api
进行这些操作的示例:
// 在你的页面文件中,例如 index.js
const api = require('../../utils/request.js');
// 获取用户列表
api.get('/users')
.then(res => {
console.log('用户列表:', res);
})
.catch(err => {
console.error('获取用户列表失败:', err);
});
// 创建新用户
api.post('/users', { name: 'John', age: 30 })
.then(res => {
console.log('创建用户成功:', res);
})
.catch(err => {
console.error('创建用户失败:', err);
});
// 更新用户信息
api.put('/users/1', { name: 'John Doe', age: 31 })
.then(res => {
console.log('更新用户成功:', res);
})
.catch(err => {
console.error('更新用户失败:', err);
});
// 删除用户
api.delete('/users/1')
.then(res => {
console.log('删除用户成功:', res);
})
.catch(err => {
console.error('删除用户失败:', err);
});
通过上述封装和使用案例,可以更简洁、统一地管理微信小程序中的网络请求,极大地提升代码的可维护性和可读性。
🔎2.wx.uploadFile上传文件
🦋2.1 微信小程序端
- 在小程序页面中添加一个按钮,用于选择图片并上传。
<!-- index.wxml -->
<view class="container">
<button bindtap="chooseImage">选择图片</button>
</view>
- 在逻辑文件中实现
chooseImage
方法。
// index.js
Page({
chooseImage() {
const that = this;
wx.chooseImage({
count: 1, // 一次选择一张图片
sizeType: ['compressed'], // 可以指定是原图还是压缩图
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
success(res) {
const tempFilePath = res.tempFilePaths[0];
wx.uploadFile({
url: 'https://your-server-url/upload', // 替换为你的服务器地址
filePath: tempFilePath,
name: 'file', // 文件的 key,后端可以通过这个 key 获取文件
formData: {
'user': 'test' // 其他需要的表单数据
},
success(uploadRes) {
console.log('上传成功:', uploadRes.data);
},
fail(error) {
console.error('上传失败:', error);
}
});
}
});
}
});
🦋2.2 后端 Java
- 使用 Spring Boot 创建一个简单的后端服务。
// build.gradle
plugins {
id 'org.springframework.boot' version '2.7.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
test {
useJUnitPlatform()
}
- 创建一个控制器来处理文件上传。
// UploadController.java
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@RestController
public class UploadController {
@PostMapping("/upload")
public ResponseEntity<Map<String, Object>> handleFileUpload(@RequestParam("file") MultipartFile file) {
Map<String, Object> response = new HashMap<>();
if (file.isEmpty()) {
response.put("message", "上传失败,文件为空");
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
try {
// 文件保存路径,这里保存到本地项目目录下
String filePath = System.getProperty("user.dir") + "/" + file.getOriginalFilename();
File dest = new File(filePath);
file.transferTo(dest);
response.put("message", "上传成功");
response.put("filePath", filePath);
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (IOException e) {
response.put("message", "上传失败,服务器错误");
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
- 启动 Spring Boot 应用。
// DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
🔎3.wx.downloadFile下载文件
🦋3.1 微信小程序端
- 在小程序页面中添加一个按钮,用于触发文件下载。
<!-- index.wxml -->
<view class="container">
<button bindtap="downloadFile">下载文件</button>
</view>
- 在逻辑文件中实现
downloadFile
方法。
// index.js
Page({
downloadFile() {
const url = 'https://your-server-url/path/to/file.pdf'; // 替换为你的文件URL
wx.downloadFile({
url: url,
success(res) {
if (res.statusCode === 200) {
const filePath = res.tempFilePath;
wx.saveFile({
tempFilePath: filePath,
success(saveRes) {
console.log('文件已保存到本地:', saveRes.savedFilePath);
wx.showToast({
title: '下载成功',
icon: 'success',
duration: 2000
});
},
fail(saveErr) {
console.error('文件保存失败:', saveErr);
wx.showToast({
title: '保存失败',
icon: 'none',
duration: 2000
});
}
});
} else {
console.error('下载失败:', res.statusCode);
wx.showToast({
title: '下载失败',
icon: 'none',
duration: 2000
});
}
},
fail(error) {
console.error('下载失败:', error);
wx.showToast({
title: '下载失败',
icon: 'none',
duration: 2000
});
}
});
}
});
🔎4.WebSocket
微信小程序使用 WebSocket 与服务器进行通信的过程包括以下几个步骤:在小程序端建立 WebSocket 连接,发送和接收消息,以及在服务端处理 WebSocket 消息。
🦋4.1 小程序端代码
首先,在小程序中编写 WebSocket 客户端代码。假设你的小程序项目结构如下:
- pages/
- index/
- index.js
- index.wxml
- index.wxss
- app.js
☀️4.1.1 index.js
Page({
data: {
message: '', // 用户输入的消息
messages: [] // 收到的消息列表
},
onLoad() {
this.connectWebSocket();
},
// 建立 WebSocket 连接
connectWebSocket() {
const that = this;
wx.connectSocket({
url: 'ws://yourserver.com/websocket', // 替换为你的 WebSocket 服务器地址
success() {
console.log('WebSocket 连接成功');
},
fail() {
console.log('WebSocket 连接失败');
}
});
wx.onSocketOpen(function() {
console.log('WebSocket 已打开');
});
wx.onSocketMessage(function(res) {
console.log('收到服务器消息:', res.data);
that.setData({
messages: [...that.data.messages, res.data]
});
});
wx.onSocketError(function() {
console.log('WebSocket 错误');
});
wx.onSocketClose(function() {
console.log('WebSocket 已关闭');
});
},
// 发送消息
sendMessage() {
if (this.data.message) {
wx.sendSocketMessage({
data: this.data.message,
success() {
console.log('消息发送成功');
},
fail() {
console.log('消息发送失败');
}
});
}
},
// 处理输入框的输入
handleInput(e) {
this.setData({
message: e.detail.value
});
}
});
☀️4.1.2 index.wxml
<view class="container">
<input bindinput="handleInput" placeholder="输入消息" />
<button bindtap="sendMessage">发送</button>
<view>
<block wx:for="{{messages}}" wx:key="*this">
<text>{{item}}</text>
</block>
</view>
</view>
☀️4.1.3 index.wxss
.container {
padding: 20px;
}
input {
width: 80%;
margin-bottom: 20px;
}
button {
margin-bottom: 20px;
}
view {
margin-top: 20px;
}
🦋4.2 服务端代码
服务端可以使用 Node.js 搭建一个简单的 WebSocket 服务器。
☀️4.2.1 server.js
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws) => {
console.log('客户端已连接');
ws.on('message', (message) => {
console.log('收到消息:', message);
ws.send(`服务器收到消息:${message}`);
});
ws.on('close', () => {
console.log('客户端已断开连接');
});
ws.on('error', (error) => {
console.error('WebSocket 错误:', error);
});
});
console.log('WebSocket 服务器运行在 ws://localhost:8080');
🦋4.3 代码注释
小程序端代码解释:
-
connectWebSocket: 建立 WebSocket 连接并设置各种事件处理函数。
wx.connectSocket
: 连接到 WebSocket 服务器。wx.onSocketOpen
: 连接成功后触发。wx.onSocketMessage
: 收到服务器消息时触发。wx.onSocketError
: 连接发生错误时触发。wx.onSocketClose
: 连接关闭时触发。
-
sendMessage: 将用户输入的消息通过 WebSocket 发送到服务器端。
wx.sendSocketMessage
: 发送 WebSocket 消息。
-
handleInput: 处理用户输入,将输入内容保存到
data.message
中。
服务端代码解释:
WebSocket.Server
: 创建一个 WebSocket 服务器,监听指定端口。server.on('connection')
: 当有客户端连接时触发。ws.on('message')
: 收到客户端消息时触发。ws.on('close')
: 客户端断开连接时触发。ws.on('error')
: 连接发生错误时触发。
🚀感谢:给读者的一封信
亲爱的读者,
我在这篇文章中投入了大量的心血和时间,希望为您提供有价值的内容。这篇文章包含了深入的研究和个人经验,我相信这些信息对您非常有帮助。
如果您觉得这篇文章对您有所帮助,我诚恳地请求您考虑赞赏1元钱的支持。这个金额不会对您的财务状况造成负担,但它会对我继续创作高质量的内容产生积极的影响。
我之所以写这篇文章,是因为我热爱分享有用的知识和见解。您的支持将帮助我继续这个使命,也鼓励我花更多的时间和精力创作更多有价值的内容。
如果您愿意支持我的创作,请扫描下面二维码,您的支持将不胜感激。同时,如果您有任何反馈或建议,也欢迎与我分享。
再次感谢您的阅读和支持!
最诚挚的问候, “愚公搬代码”
- 点赞
- 收藏
- 关注作者
评论(0)