在uni-app中,发起HTTP请求主要通过uni.request方法实现。
Get请求
使用uni.request请求api,并且将 method参数设置为GET,有参数的话直接data:{}传递,
success是请求成功回调函数,fail是失败函数
<button @click="getTime"> 点击获取时间</button>getTime(){uni.request({url: 'http://localhost:5017/test', // 接口地址method: 'GET', // 请求方法data: {id: '1', },success: (res) => {console.log('GET 请求成功返回服务器时间', res.data);},fail: (err) => {console.log('GET 请求失败', err);}});}
测试一下后端为.net6 api

请求成功!get将参数拼接在请求url后面

Post请求
post请求如果发送的是json数据格式要加上
header: {
'Content-Type': 'application/json' // 如果需要以JSON格式发送数据
},头部请求信息设置参数格式是json格式
<button @click="send">post请求</button>send(){uni.request({url: 'http://localhost:5017/login', // 接口地址method: 'POST', // 请求方法data: {username: 'zhangsan',password: '12356'},header: {'Content-Type': 'application/json' // 如果需要以JSON格式发送数据},success: (res) => {console.log('POST 请求成功', res.data);},fail: (err) => {console.log('POST 请求失败', err);}});}
后端代码

uni-app的uni.request方法是异步的,因此需要通过success和fail回调处理响应。- 如果接口要求认证(例如
token),可以在header里添加Authorization字段。
