uniapp 网络请求代码及实例
时间: 2023-10-05 07:06:40 浏览: 96
uniapp 请求代码封装
1. 发送GET请求
```
uni.request({
url: 'https://www.example.com/api',
method: 'GET',
data: {
param1: 'value1',
param2: 'value2'
},
success: function(res) {
console.log(res.data);
},
fail: function(res) {
console.log(res.errMsg);
}
});
```
2. 发送POST请求
```
uni.request({
url: 'https://www.example.com/api',
method: 'POST',
data: {
param1: 'value1',
param2: 'value2'
},
success: function(res) {
console.log(res.data);
},
fail: function(res) {
console.log(res.errMsg);
}
});
```
3. 发送带header的请求
```
uni.request({
url: 'https://www.example.com/api',
method: 'GET',
header: {
'Authorization': 'Bearer token'
},
success: function(res) {
console.log(res.data);
},
fail: function(res) {
console.log(res.errMsg);
}
});
```
4. 发送带cookie的请求
```
uni.request({
url: 'https://www.example.com/api',
method: 'GET',
header: {
'cookie': 'sessionId=xxxxx'
},
success: function(res) {
console.log(res.data);
},
fail: function(res) {
console.log(res.errMsg);
}
});
```
5. 上传文件
```
uni.uploadFile({
url: 'https://www.example.com/api',
filePath: 'tempFilePath',
name: 'file',
formData: {
param1: 'value1',
param2: 'value2'
},
success: function(res) {
console.log(res.data);
},
fail: function(res) {
console.log(res.errMsg);
}
});
```
6. 下载文件
```
uni.downloadFile({
url: 'https://www.example.com/file',
success: function(res) {
if (res.statusCode === 200) {
console.log(res.tempFilePath);
}
},
fail: function(res) {
console.log(res.errMsg);
}
});
```
阅读全文