uniapp如何发送post请求
在uniapp中如何发送POST请求?我试了uni.request方法,但不知道如何正确设置请求头和请求体参数。希望能提供一个完整的示例代码,包括如何处理请求失败的情况。
2 回复
在uni-app中,使用uni.request发送POST请求:
uni.request({
url: 'https://example.com/api',
method: 'POST',
data: {
key1: 'value1',
key2: 'value2'
},
success: (res) => {
console.log('请求成功', res.data);
},
fail: (err) => {
console.log('请求失败', err);
}
});
记得在manifest.json中配置网络权限。
在 UniApp 中发送 POST 请求,可以使用内置的 uni.request 方法。以下是详细步骤和示例代码:
基本语法
uni.request({
url: 'https://example.com/api/post', // 请求的接口地址
method: 'POST', // 请求方法,必须明确指定为 POST
data: { // 请求参数(POST 数据)
key1: 'value1',
key2: 'value2'
},
header: { // 请求头
'Content-Type': 'application/json' // 默认值,可根据需要修改
},
success: (res) => { // 请求成功回调
console.log('请求成功:', res.data);
},
fail: (err) => { // 请求失败回调
console.error('请求失败:', err);
},
complete: () => { // 请求完成回调(无论成功或失败)
console.log('请求完成');
}
});
关键参数说明
- url:目标 API 地址(需确保域名在
manifest.json的合法域名列表中)。 - method:必须设为
'POST'。 - data:传递的 POST 数据(对象形式)。
- header:可设置
Content-Type(例如application/x-www-form-urlencoded用于表单数据)。
示例:提交表单数据
uni.request({
url: 'https://api.example.com/login',
method: 'POST',
data: {
username: 'admin',
password: '123456'
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: (res) => {
if (res.statusCode === 200) {
uni.showToast({ title: '登录成功' });
}
},
fail: (err) => {
uni.showToast({ title: '网络错误', icon: 'error' });
}
});
注意事项
- 域名配置:在 H5 端需配置跨域,真机调试时需在
manifest.json的 “App模块配置” 或 “H5配置” 中添加合法域名。 - 异步处理:可使用
Promise或async/await封装以提高代码可读性。
通过以上方法,即可在 UniApp 中实现 POST 请求。

