uni-ajax网络请求库使用
warning:
这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
uni-ajax 是一个基于 Promise 的轻量级 HTTP 请求库,主要用于微信小程序和 Uni-app 开发。以下是一个使用 uni-ajax 发送 GET 和 POST 请求的示例代码:
// 引入 uni-ajax 模块
import uniAjax from 'uni-ajax';
// 发送 GET 请求
uniAjax({
url: 'https://your-api-endpoint.com/get', // 你的 API 接口
method: 'GET',
data: {
param1: 'value1',
param2: 'value2'
}
}).then(response => {
console.log('GET Response:', response.data);
}).catch(error => {
console.error('GET Error:', error);
});
// 发送 POST 请求
uniAjax({
url: 'https://your-api-endpoint.com/post', // 你的 API 接口
method: 'POST',
data: {
field1: 'value1',
field2: 'value2'
}
}).then(response => {
console.log('POST Response:', response.data);
}).catch(error => {
console.error('POST Error:', error);
});在这个示例中,我们首先导入了 uni-ajax 模块,然后使用它来发送 GET 和 POST 请求。我们通过 url 指定请求的目标地址,通过 method 指定请求的类型,并且可以通过 data 属性传递请求参数。请求结果会以 Promise 的形式返回,使用 .then() 处理成功的响应,使用 .catch() 处理可能发生的错误。
评论已关闭