前端向后台发送获取数据网络请求,使用uni.request() https://uniapp.dcloud.io/api/request/request
一、uni.request请求
methods:{
getData(){
uni.request({
url:'https://www.example.com/request', //仅为示例,并非真实接口地址。
data: {
text: 'uni.request'
},
header: {
'custom-header': 'hello' //自定义请求头信息
},
success:res=> {
console.log(res)
if(res.data.status!==0){
return uni.showToast({
title:"数据获取失败"
})
}
this.data=res.data.messege
}
})
}
}
二、封装uni.request请求
网络请求一般都会封转成一个公用的工具类,专门处理网络请求。这样集中处理接口地址,清晰、方便且高效。具体如下:
(1)在项目下新建【http】文件夹,新建【api.js】文件
const BASE_URL="http://192.168.34.121:8080"
export const myRequest=(options)=>{
return new Promise((resolve,reject)=>{
uni.request({
url:BASE_URL+options.url,
method:options.method || 'GET',
data:options.data || {},
success:(res)=>{
resolve(res)
},
fail:(err)=>{
uni.showToast({
title:"请求接口失败"
})
reject(err)
}
})
})
}
(2)在【main.js】将request请求挂在在原型链上(全局使用)
import {myRequest} from "./http/api.js"
// 挂载全局
Vue.prototype.$myRequest=myRequest
(3)在页面或组件中通过【this.$myRequest()】使用封装好的请求接口
methods:{
saveData(){
var param={
cardImage:this.cardImage,
cardInfo:this.cardInfo,
type:this.type
}
console.log(param)
this.$myRequest({
url:"card/save",
method:"POST",
data:param
}).then(res=>{
console.log(res)
if(res.data.respCode=="00000"){}else{}
uni.showToast({title:res.data.respDesc,icon:"none"})
uni.navigateTo({
url:"/pages/index/index"
})
}).catch(err=>{
console.log(err)
})
}