在main.js文件中配置:
//Vue.prototype.$baseUrl="http://192.168.1.164/api" //线下接口
Vue.prototype.$baseUrl="https://m.demo.com/api" //线上接口
在demo.vue页面中请求:
//GET-请求数据
getInfo(){
uni.request({
url: `${this.$baseUrl}/api-demo/getDemoById?lid=${lid}&page=${this.page}&pagesize=${this.pagesize}`, //这里的lid,page,pagesize只能是数字或字母
method: 'GET',
success: (res)=>{},
fail: (err)=>{}
})
}
注:携带在url里的参数只能是数字或字母,不能是中文字符。若参数中含有中文字符,比如搜索功能,则需要将参数携带在data中。如下:data:params
//POST-发送json格式请求
sendInfo(){
let params = {
"phone":this.userphone,
"name":this.username
}
uni.request({
url: `${this.$baseUrl}/api-demo/send`,
method: 'POST',
data: params,
success: (res)=>{},
fail: (err)=>{}
})
}
//POST-发送FormData格式请求
sendInfo(){
let params = {
"phone":this.userphone,
"name":this.username
}
let headers={
"Content-Type":"application/x-www-form-urlencoded" //设置一下请求头即可
}
uni.request({
url: `${this.$baseUrl}/api-demo/send`,
method: 'POST',
header: headers,
data: params,
success: (res)=>{},
fail: (err)=>{}
})
}
//请求接口时携带token
sendInfo(){
let params = {
"phone":this.userphone,
"name":this.username
}
let headers={
"Content-Type":"application/x-www-form-urlencoded",
"Token":`this.userToken` //设置一下token即可
}
uni.request({
url: `${this.$baseUrl}/api-demo/send`,
method: 'POST',
header: headers,
data: params,
success: (res)=>{},
fail: (err)=>{}
})
}