基本用例
GET 请求
typescript
import { un } from "@uni-helper/uni-network";
// 请求特定 ID 的用户数据
un.get("/user?ID=12345")
.then((response) => {
// 处理响应
console.log("response", response);
})
.catch((error) => {
// 处理错误
console.log("error", error);
})
.finally(() => {
// 总是会执行
});
// 上述请求和以下等同
un.get("/user", {
params: {
ID: "12345",
},
})
.then((response) => {
console.log("response", response);
})
.catch((error) => {
console.log("error", error);
})
.finally(() => {
// 总是会执行
});名称
un 是 uni 和 network 的首字母缩写。如果你不习惯这个名称,你可以在导入时自行调整,比如使用 uniNetwork:import { un as uniNetwork } from '@uni-helper/uni-network';。
使用 async/await 的 GET 请求
typescript
import { un } from "@uni-helper/uni-network";
async function getUser() {
try {
const response = await un.get("/user?ID=12345");
console.log(response);
} catch (error) {
console.error(error);
}
}POST 请求
typescript
import { un } from "@uni-helper/uni-network";
un.post("/user", {
firstName: "Fred",
lastName: "Flintstone",
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(() => {});上传文件
un.upload 走 uni.uploadFile。filePath 和 files 必填一个(files 不支持小程序),name 是服务器读取文件的 key。
typescript
import { un } from "@uni-helper/uni-network";
uni.chooseImage({
success: (res) => {
un.upload("https://example.com/upload", {
filePath: res.tempFilePaths[0],
name: "file",
// 会作为额外的 form data 一起提交
formData: { userId: "12345" },
})
.then((response) => {
// upload 适配器的 data 是服务器返回的字符串
console.log(response.status, response.data);
})
.catch((error) => {
console.log(error);
});
},
});下载文件
un.download 走 uni.downloadFile。不传 filePath 时文件存到临时路径,路径在 response.tempFilePath;传了 filePath 则原样返回在 response.filePath。
typescript
import { un } from "@uni-helper/uni-network";
// 下载到临时路径
un.download("https://example.com/file.pdf").then((response) => {
console.log(response.tempFilePath);
});
// 下载到指定路径
un.download("https://example.com/file.pdf", {
filePath: "/user/downloads/file.pdf",
}).then((response) => {
console.log(response.filePath);
});上传和下载都可以在配置里传进度回调,见请求配置。
并发请求
typescript
import { un } from "@uni-helper/uni-network";
function getUserAccount() {
return un.get("/user/12345");
}
function getUserPermissions() {
return un.get("/user/12345/permissions");
}
Promise.all([getUserAccount(), getUserPermissions()]).then((responses) => {
const userAccount = responses[0];
const userPermissions = responses[1];
});基本用例应该能让你初步上手 @uni-helper/uni-network。你可以动手尝试一下,也可以继续往下阅读。