目录
创建文件
根目录下新建common文件夹,内建lib文件夹(可以省略),最后新建request.js文件(名称随意)
写入配置
接口是我从网上找的一组数据接口,这里做个演示
const baseUrl = 'http://121.40.58.83:5001/api'
const request = (url='',data={},type='GET',header={})=>{
return new Promise((resolve,reject)=>{
uni.request({
url:baseUrl+url,
data:data,
type:type,
header: header,
dataType: 'json',
}).then((response)=>{
setTimeout(function(){
uni.hideLoading()
},200)
let [error, res] = response
resolve(res.data);
}).catch(error=>{
let [err, res] = error;
reject(err)
})
})
}
export default request
引用
在main.js内引用
import request from 'common/lib/request.js'
Vue.prototype.$H = request
使用
在想要使用的页面进行使用
methods:{
getInfo(){
this.$H('/index_category').then(res=>{
console.log(res)
})
}
},
H5端适配设置
最开始的几段是判定是否为H5端,H5端存在跨域问题而小程序端不存在,所以要做单独设置
首先修改request.js文件配置
// #ifdef H5
var baseUrl = '/api'
// #endif
// #ifndef H5
var baseUrl = 'http://请求网址/api'
// #endif
const request = (url='',data={},type='GET',header={})=>{
return new Promise((resolve,reject)=>{
uni.request({
url:baseUrl+url,
data:data,
method:type,
header: header,
dataType: 'json',
}).then((response)=>{
setTimeout(function(){
uni.hideLoading()
},200)
let [error, res] = response
resolve(res.data);
}).catch(error=>{
let [err, res] = error;
reject(err)
})
})
}
export default request
然后打开manifest.json,点击源码视图
在{}内最后接上写入内容
"h5" : {
"router" : {
"mode" : "hash"
},
"devServer" : {
"https" : false,
"proxy" : {
"/api" : {
"target" : "http://121.40.58.83:5001/api",
"changeOrigin" : true,
"ws" : true,
"pathRewrite" : {
"^/api" : ""
}
}
}
}
}
功能全面版配置文件
export default {
common:{
// #ifdef H5
baseUrl : '/api'
// #endif
// #ifndef H5
baseUrl : 'http://请求网址/api'
// #endif
header:{
'Content-Type':'application/json;charset=UTF-8',
'Content-Type':'application/x-www-form-urlencoded'
},
data:{},
method:'GET',
dataType:'json'
},
request(options={}){
options.url = this.common.baseUrl + options.url,
options.header = options.header || this.common.header,
options.data = options.data || this.common.data,
options.method = options.method || this.common.method,
options.dataType = options.dataType || this.common.dataType
return new Promise((res,rej)=>{
uni.request({
...options,
success: (result) => {
if(result.statusCode != 200){
uni.showToast({
title:res.data.msg ||'服务器端失败',
duration: 1000,
icon:'none'
})
return rej()
}
let data = result.data.data
res(data)
},
fail: (error) => {
uni.showToast({
title: error.errMsg || '请求失败',
duration: 1000,
icon:'none'
});
return rej()
}
})
})
}
get(url,data={},options={}){
options.url = url,
options.data = data,
options.method = 'GET',
return this.request(options)
},
post(url,data={},options={}){
options.url = url,
options.data = data,
options.method = 'POST',
return this.request(options)
},
put(url,data={},options={}){
options.url = url,
options.data = data,
options.method = 'PUT',
return this.request(options)
},
del(url,data={},options={}){
options.url = url,
options.data = data,
options.method = 'DEL',
return this.request(options)
}
}