在 uni-app 中使用 uni.request 发起网络请求,由于业务的需要,一些请求需要携带请求头访问,于是我对该请求方法进行了封装。
新建 common/app.js
export const apiBaseUrl
= 'http://192.168.1.104:8091/sports-tms/'
const noToken
= [
'sys/wxlogin'
];
const request = (method
, methodType
, data
, callback
, hideLoading
) => {
var headers
= {
'content-type': 'application/x-www-form-urlencoded'
};
if (!(noToken
.indexOf(method
) >= 0)) {
let userToken
= uni
.getStorageSync('x-access-token')
if (!userToken
) {
uni
.navigateTo({
url
: '/pages/login/login'
})
return false;
} else {
headers
['x-access-token'] = userToken
}
}
if (!hideLoading
) {
uni
.showLoading({
title
: '加载中'
});
}
uni
.request({
url
: apiBaseUrl
+ method
,
data
: data
,
header
: headers
,
method
: methodType
,
success
: (response
) => {
if (!hideLoading
) {
uni
.hideLoading();
}
console
.log(response
.data
)
const result
= response
.data
if (result
.code
== 500) {
uni
.showToast({
icon
: 'none',
title
: result
.message
,
duration
: 1500
})
} else {
console
.log(result
)
callback(result
)
}
},
complete
: () => {
uni
.hideLoading();
},
fail
: (error
) => {
uni
.hideLoading();
if (error
&& error
.response
) {
showError(error
.response
);
}
}
})
}
const showError = error
=> {
let errorMsg
= ''
switch (error
.status
) {
case 400:
errorMsg
= '请求参数错误'
break
case 401:
errorMsg
= '未授权,请登录'
break
case 403:
errorMsg
= '跨域拒绝访问'
break
case 404:
errorMsg
= `请求地址出错: ${error.config.url}`
break
case 408:
errorMsg
= '请求超时'
break
case 500:
errorMsg
= '服务器内部错误'
break
case 501:
errorMsg
= '服务未实现'
break
case 502:
errorMsg
= '网关错误'
break
case 503:
errorMsg
= '服务不可用'
break
case 504:
errorMsg
= '网关超时'
break
case 505:
errorMsg
= 'HTTP版本不受支持'
break
default:
errorMsg
= error
.msg
break
}
uni
.showToast({
title
: errorMsg
,
icon
: 'none',
duration
: 1000,
complete
: function() {
setTimeout(function() {
uni
.hideToast();
}, 1000);
}
});
}
export const wxlogin = (data
, callback
, hideLoading
) => request('sys/wxlogin', 'POST', data
, callback
, hideLoading
);
修改 main.js
主要增加 import * as request from './common/api' 和 Vue.prototype.$api = {request}
import Vue
from 'vue'
import App
from './App'
import store
from './store'
import uView
from "uview-ui";
import * as request
from './common/api'
Vue
.use(uView
);
Vue
.config
.productionTip
= false
Vue
.prototype
.$store
= store
Vue
.prototype
.$api
= {request
};
App
.mpType
= 'app'
const app
= new Vue({
store
,
...App
})
app
.$mount()
在 common/api.js 中定义接口
export const wxlogin = (data
, callback
, hideLoading
) => request('sys/wxlogin', 'POST', data
, callback
, hideLoading
);
三个参数
data:该接口需要传递的参数callback:请求完成的回调函数uniHideLoading:是否显示加载中…,默认为 true
使用接口
this.$api
.request
.wxlogin({
code
: that
.code
,
encryptedData
: encryptedData
,
iv
: iv
}, res
=> {
console
.log(res
)
uni
.setStorageSync("x-access-token", res
.result
.token
)
uni
.setStorageSync("userId", res
.result
.userInfo
.id
)
uni
.switchTab({
url
: '/pages/educational/educational'
})
});