1. 普通網(wǎng)絡(luò)請求
1.1 未封裝前index.vue頁面使用
getMachineNum:function(){
var timestamp = Date.parse(new Date());//時(shí)間戳
var token = uni.getStorageSync(_self.sessionKey);
var device = "wxapp";
var ver = "1.1.30";
uni.request({
url: this.siteBaseUrl + 'machine/index',
method: 'GET',
data: {
token : token,
timestamp : timestamp,
device : device,
ver : ver
},
success: res => {
console.log("getMachineNum success:" + JSON.stringify(res));
if (res.data.code == "-1") {//登錄失效
uni.showToast({
title: res.data.msg,
mask: false,
duration: 1500
});
} else if (res.data.code == "0") {
var data = res.data.data;
_self.onlineNum = data.onlineNum;
_self.machineNum = data.machineNum;
}else {
console.log("未處理的結(jié)果碼");
}
},
fail: (e) => {
console.log("getMachineNum fail:" + JSON.stringify(e));
},
complete: () => {}
});
},
請求結(jié)果
{
"data": {
"code": "0",
"msg": "success",
"data": {
"machineNum": 124,
"onlineNum": 1,
}
},
"header": {
"Server": "nginx/1.14.0",
"Date": "Thu, 11 Apr 2019 03:08:20 GMT",
"Content-Type": "application/json;charset=utf-8;",
"Transfer-Encoding": "chunked",
"Connection": "keep-alive",
"X-Powered-By": "PHP/7.1.16"
},
"statusCode": 200,
"cookies": [],
"errMsg": "request:ok"
}
1.2 main.js中封裝網(wǎng)絡(luò)請求
- main.js
Vue.prototype.sendRequest= function(param,backpage, backtype){
var _self = this,
url = param.url,
data = param.data || {},
header = param.header,
token = "";
//拼接完整請求地址
var requestUrl = this.siteBaseUrl + url;
//固定參數(shù)
if(!data.token){//如果參數(shù)中無token(除了小程序第一次通過code獲取token的接口默認(rèn)參數(shù)token = login,其他接口token參數(shù)都是在本地緩存中獲取)
token = uni.getStorageSync(this.sessionKey);
if(!token){//本地?zé)otoken需重新登錄
_self.login(backpage, backtype);
return;
}else{
data.token = token;
}
}
var timestamp = Date.parse(new Date());//時(shí)間戳
data["timestamp"] = timestamp;
data["device"] = "wxapp";//data["device"] = "iosapp";
data["ver"] = "1.1.30";//data["ver"] = "1.0.0";
//GET或POST
if(param.method){
param.method = param.method.toUpperCase();//小寫改為大寫
}
//網(wǎng)絡(luò)請求
uni.request({
url: requestUrl,
method: param.method || "GET",
header: header || {'content-type' : "application/json"},
data: data,
success: res => {
console.log("網(wǎng)絡(luò)請求success:" + JSON.stringify(res));
if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤
uni.showModal({
content:"" + res.errMsg
});
return;
}
if (res.data.code) {//返回結(jié)果碼code判斷:0成功,1錯(cuò)誤,-1未登錄
if (res.data.code == "-1") {
_self.login(backpage, backtype);
return;
}
if (res.data.code != "0") {
uni.showModal({
showCancel:false,
content:"" + res.data.msg
});
return;
}
} else{
uni.showModal({
showCancel:false,
content:"" + res.data.msg
});
return;
}
typeof param.success == "function" && param.success(res.data);
},
fail: (e) => {
console.log("網(wǎng)絡(luò)請求fail:" + JSON.stringify(e));
uni.showModal({
content:"" + res.errMsg
});
typeof param.fail == "function" && param.fail(res.data);
},
complete: () => {
console.log("網(wǎng)絡(luò)請求complete");
uni.hideLoading();
typeof param.complete == "function" && param.complete(res.data);
return;
}
});
}
Vue.prototype.login = function(backpage, backtype){
var _self = this;
uni.login({
success:function(res){
_self.requestData({
url : "user/login",
data : {
code : res.code,
token : "login"
},
success : function(res2){
if (res2.data.errCode == "0") {//用戶存在:存儲(chǔ)token
uni.setStorageSync(_self.sessionKey,res2.data.token);
} else if (res2.data.errCode == "0") {//用戶不存在:調(diào)轉(zhuǎn)到綁定頁面
uni.redirectTo({url:'../binding/binding?backpage='+backpage+'&backtype='+backtype});
return false;
}
}
},backpage, backtype)
},
fail:function(e){
console.log("微信login接口調(diào)用失敗:" + JSON.stringify(e));
}
});
return;
}
Vue.prototype.siteBaseUrl = 'https://api.uchat.com.cn/';
Vue.prototype.sessionKey = "sess_jk";
- 封裝后index.vue頁面get請求調(diào)用
getMachineNum:function(){
this.sendRequest({
url : "machine/index",
success : function(res){
console.log("getMachineNum success:" + JSON.stringify(res));
var data = res.data;
_self.onlineNum = data.onlineNum || 0;
_self.machineNum = data.machineNum || 0;
},
fail:function(e){
console.log("getMachineNum fail:" + JSON.stringify(e));
}
},'../myhome/myhome','2')
}
注意
:頁面POST請求header需配置為 {'content-type' : "application/x-www-form-urlencoded"}币呵,如:
initData:function () {
this.sendRequest({
url : "CompanyTeam/teamInfo",
data : {ct_id : ct_id},
method : "POST",
header: {'content-type' : "application/x-www-form-urlencoded"},
success:function (res) {
console.log("獲取數(shù)據(jù):" + JSON.stringify(res));
}
},"/pages/machineGroupOutput/machineGroupOutput","1")
},
故禾嫉,可對網(wǎng)絡(luò)請求封裝繼續(xù)優(yōu)化始腾。
1.3 網(wǎng)絡(luò)請求封裝優(yōu)化
- main.js
Vue.prototype.sendRequest = function(param,backpage, backtype){
var _self = this,
url = param.url,
method = param.method,
header = {},
data = param.data || {},
token = "",
hideLoading = param.hideLoading || false;
//拼接完整請求地址
var requestUrl = this.siteBaseUrl + url;
//固定參數(shù):僅僅在小程序綁定頁面通過code獲取token的接口默認(rèn)傳遞了參數(shù)token = login
if(!data.token){//其他業(yè)務(wù)接口傳遞過來的參數(shù)中無token
token = uni.getStorageSync(this.sessionKey);//參數(shù)中無token時(shí)在本地緩存中獲取
console.log("當(dāng)前token:" + token);
if(!token){//本地?zé)otoken需重新登錄(退出時(shí)清緩存token)
_self.login(backpage, backtype);
return;
}else{
data.token = token;
}
}
var timestamp = Date.parse(new Date());//時(shí)間戳
data["timestamp"] = timestamp;
// #ifdef MP-WEIXIN
data["device"] = "wxapp";
data["ver"] = "1.1.30";
// #endif
// #ifdef APP-PLUS || H5
data["device"] = "iosapp";
data["ver"] = "1.0.0";
// #endif
//請求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
if(method){
method = method.toUpperCase();//小寫改為大寫
if(method=="POST"){
header = {'content-type' : "application/x-www-form-urlencoded"};
}else{
header = {'content-type' : "application/json"};
}
}else{
method = "GET";
header = {'content-type' : "application/json"};
}
//用戶交互:加載圈
if (!hideLoading) {
uni.showLoading({title:'加載中...'});
}
console.log("網(wǎng)絡(luò)請求start");
//網(wǎng)絡(luò)請求
uni.request({
url: requestUrl,
method: method,
header: header,
data: data,
success: res => {
console.log("網(wǎng)絡(luò)請求success:" + JSON.stringify(res));
if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤
uni.showModal({
content:"" + res.errMsg
});
return;
}
if (res.data.code) {//返回結(jié)果碼code判斷:0成功,1錯(cuò)誤,-1未登錄(未綁定/失效/被解綁)
if (res.data.code == "-1") {
_self.login(backpage, backtype);
return;
}
if (res.data.code != "0") {
uni.showModal({
showCancel:false,
content:"" + res.data.msg
});
return;
}
} else{
uni.showModal({
showCancel:false,
content:"No ResultCode:" + res.data.msg
});
return;
}
typeof param.success == "function" && param.success(res.data);
},
fail: (e) => {
console.log("網(wǎng)絡(luò)請求fail:" + JSON.stringify(e));
uni.showModal({
content:"" + e.errMsg
});
typeof param.fail == "function" && param.fail(e.data);
},
complete: () => {
console.log("網(wǎng)絡(luò)請求complete");
if (!hideLoading) {
uni.hideLoading();
}
typeof param.complete == "function" && param.complete();
return;
}
});
}
- 頁面POST請求調(diào)用
initData:function () {
this.sendRequest({
url : "CompanyTeam/teamInfo",
method : "POST",
data : {ct_id : ct_id},
hideLoading : true,
success:function (res) {
console.log("獲取數(shù)據(jù):" + JSON.stringify(res));
}
},"/pages/machineGroupOutput/machineGroupOutput","1")
},
拓展:設(shè)置網(wǎng)絡(luò)請求為同步可參考Promise 封裝。大致可分為三種方案:請求嵌套(異步方式的成功回調(diào)里獲取數(shù)據(jù)后再采用異步方式請求)咬扇、promise 或者await,具體實(shí)現(xiàn)可自行實(shí)踐赔退,這里不詳細(xì)敘述忌堂。
2. 文件上傳封裝
(1) 未封裝前index.vue頁面使用
commitUnqualifiedInfoAndFile:function(filePath){
uni.uploadFile({
url: 'http://' + _self.getIP() + '/' + 'ticket/toCheck',
filePath: filePath,
name: 'image',
formData: {
token : uni.getStorageSync(this.sessionKey),
timestamp : Date.parse(new Date()),
style_id : "7",
production_id : "SCD778",
qualified_num:0
},
success: (res) => {
console.log("res:" + JSON.stringify(res));//json對象轉(zhuǎn)json字符串
console.log("statusCode:" + res.statusCode);
console.log("uniapp上傳文件api返回的data是字符串類型:"+ res.data);
var dataString = res.data;//json字符串
var res = JSON.parse(dataString);//json字符串轉(zhuǎn)json對象
console.log("code:"+ res.code);
console.log("msg:"+ res.msg);
uni.showToast({
title:res.data.msg ? res.data.msg : "成功",
icon:'none'
});
console.log("data_1:"+ res.data.qualified_num);
console.log("data_2:"+ res.data.failed_num);
},
fail: (e) => {
console.log("網(wǎng)絡(luò)請求fail");
},
complete: () => {
console.log("網(wǎng)絡(luò)請求complete");
}
});
},
備注:后臺返回的data值如下
{
"data": {
"msg": "質(zhì)檢完成",
"qualified_num": 41,
"failed_num": "17"
},
"code": "0",
"msg": "success"
}
打印結(jié)果:uniapp上傳文件api返回的data是字符串類型,需先將data轉(zhuǎn)換為json對象拴曲,之后再取里面的值
挣郭。
(2) main.js中封裝網(wǎng)絡(luò)請求
//上傳文件
Vue.prototype.uploadFileRequest = function(param){
var _self = this,
url = param.url || "",
path = param.path || "",
name = param.name || "file",
data = param.data || {},
token = "";
if(url == ""){
url = _self.getUploadFileUrl();//默認(rèn)的上傳文件地址
}else{
url = "http://" + this.getIP() + "/" + url;
}
if(!data.token){
token = uni.getStorageSync(this.sessionKey);
console.log("當(dāng)前token:" + token);
if(!token){
uni.redirectTo({url:'/pages/login1/login1'});
return;
}else{
data.token = token;
}
}
var timestamp = Date.parse(new Date());//時(shí)間戳
data["timestamp"] = timestamp;
console.log("網(wǎng)絡(luò)請求start:url:" + url + ",params:" +JSON.stringify(data));
uni.uploadFile({
url: url,
filePath: path,
name: name,
formData: data,
success: (res) => {
console.log("網(wǎng)絡(luò)請求success-res:" + JSON.stringify(res));//json對象轉(zhuǎn)json字符串
console.log("網(wǎng)絡(luò)請求success-statusCode:" + res.statusCode);
console.log("uniapp上傳文件api返回的data是字符串類型:" + res.data);
if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤(Error StatusCode)
uni.showToast({
/* title:res.errMsg */
title:"api錯(cuò)誤",
icon:'none'
});
return;
}
var dataString = res.data;//json字符串
var res = JSON.parse(dataString);//json字符串轉(zhuǎn)json對象
if (res.code) {
if (res.code != "0") {//Error ResultCode
uni.showToast({
title:res.msg,
icon:'none'
});
return;
}
} else {//No ResultCode
uni.showToast({
/* title:res.msg */
title:"無結(jié)果碼",
icon:'none'
});
return;
}
typeof param.success == "function" && param.success(res);
},
fail: (e) => {
console.log("網(wǎng)絡(luò)請求fail");
uni.showToast({
/* title: e.errMsg */
title:"請檢查網(wǎng)絡(luò)",
icon:'none'
});
typeof param.fail == "function" && param.fail(e.data);
},
complete: () => {
console.log("網(wǎng)絡(luò)請求complete");
typeof param.complete == "function" && param.complete();
return;
}
});
}
(3) 封裝后index.vue頁面調(diào)用
commitUnqualifiedInfoAndFile:function(filePath){
_self.uploadFileRequest({
url:'ticket/toCheck',
path: filePath,
name: 'image',
data:{
style_id : "7",
production_id : "SCD778",
qualified_num:0,
},
success: (res) => {
console.log("res:" + JSON.stringify(res));//json對象轉(zhuǎn)json字符串
uni.showToast({
title:res.data.msg ? res.data.msg : "成功",
icon:'none'
});
},
fail: (e) => {
},
complete: () => {
}
});
},
3. 所有網(wǎng)絡(luò)請求封裝為公用js文件
(1) http.js
const baseUrl = "http://api.liy.cn"
//網(wǎng)絡(luò)判斷
const hasNetwork = function(){
var result = true;
uni.getNetworkType({
success: function (res) {
console.log("網(wǎng)絡(luò)類型:" + res.networkType);
if(res.networkType == "none"){
uni.showToast({
title:"網(wǎng)絡(luò)未連接",
icon:'none'
});
result = false;
}
}
});
return result;
}
//登錄請求
const sendLoginRequest = function(param){
//為什么程序未執(zhí)行網(wǎng)絡(luò)變化的監(jiān)聽:網(wǎng)絡(luò)發(fā)生變化才會(huì)觸發(fā)
// uni.onNetworkStatusChange(function(res){
// // console.log("網(wǎng)絡(luò)類型:" + res.networkType + ",網(wǎng)絡(luò)連接:" + res.isConnected);
// if(!res.isConnected){
// uni.showToast({
// title:"網(wǎng)絡(luò)未連接",
// icon:'none'
// });
// return;
// }
// })
// if(!hasNetwork()){//移到頁面中判斷:適配按鈕狀態(tài)變化的邏輯
// return;
// }
var _self = this, data = param.data || {}, siteBaseUrl = baseUrl + "/";
uni.request({
url: siteBaseUrl + "user/login",
method: 'POST',
//header: {'content-type' : "application/json"},//默認(rèn)
header: {'content-type' : "application/x-www-form-urlencoded"},
data: data,
success:function(res){
console.log("網(wǎng)絡(luò)請求success:" + JSON.stringify(res));
if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤(Error StatusCode)
uni.showToast({
/* title:res.errMsg */
title:"api錯(cuò)誤",
icon:'none'
});
return;
}
if (res.data.code) {
if (res.data.code != "0") {//Error ResultCode
uni.showToast({
title:res.data.msg,
icon:'none'
});
return;
}
} else {//No ResultCode
uni.showToast({
/* title:res.data.msg */
title:"無結(jié)果碼",
icon:'none'
});
return;
}
typeof param.success == "function" && param.success(res.data);
},
fail:function(e){
console.log("網(wǎng)絡(luò)請求fail:" + JSON.stringify(e));
uni.showToast({
/* title:e.errMsg */
title:"請檢查網(wǎng)絡(luò)",
icon:'none'
});
typeof param.fail == "function" && param.fail(e.data);
},
complete:function(){
console.log("網(wǎng)絡(luò)請求complete");
typeof param.complete == "function" && param.complete();
return;
}
});
}
//封裝除登錄外的業(yè)務(wù)網(wǎng)絡(luò)請求
const sendRequest = function(param){
if(!hasNetwork()){//移到頁面中判斷:適配按鈕狀態(tài)變化的邏輯
return;
}
var _self = this,
url = param.url,
method = param.method,
header = {},
data = param.data || {},
token = "",
hideLoading = param.hideLoading || true;
//拼接完整請求地址
var requestUrl = baseUrl + "/" + url;
//固定參數(shù):僅僅在小程序綁定頁面通過code獲取token的接口默認(rèn)傳遞了參數(shù)token = login
if(!data.token){//其他業(yè)務(wù)接口傳遞過來的參數(shù)中無token
token = uni.getStorageSync(this.sessionKey);//參數(shù)中無token時(shí)在本地緩存中獲取
console.log("當(dāng)前token:" + token);
if(!token){//本地?zé)otoken需重新登錄(退出時(shí)清緩存token)
uni.redirectTo({url:'/pages/login/login'});
return;
}else{
data.token = token;
}
}
var timestamp = Date.parse(new Date());//時(shí)間戳
data["timestamp"] = timestamp;
var center_id = _self.getUserInfo().center_id || "";
data["center_id"] = center_id;
//請求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
if(method){
method = method.toUpperCase();//小寫改為大寫
if(method=="POST"){
header = {'content-type' : "application/x-www-form-urlencoded"};
}else{
header = {'content-type' : "application/json"};
}
}else{
method = "GET";
header = {'content-type' : "application/json"};
}
//用戶交互:加載圈
if (!hideLoading) {
uni.showLoading({title:'加載中...'});
}
console.log("網(wǎng)絡(luò)請求start:url:" + requestUrl + "疗韵,params:" +JSON.stringify(data));
//網(wǎng)絡(luò)請求
uni.request({
url: requestUrl,
method: method,
header: header,
data: data,
success: res => {
console.log("網(wǎng)絡(luò)請求success:" + JSON.stringify(res));
if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤
uni.showToast({
/* title: res.errMsg */
title:"api錯(cuò)誤",
icon:'none'
});
return;
}
if (res.data.code) {//返回結(jié)果碼code判斷:0成功,1錯(cuò)誤,-1未登錄(未綁定/失效/被解綁)
if (res.data.code == "-1") {
uni.redirectTo({url:'/pages/login2/login2'});
return;
}
if (res.data.code != "0") {//code為1失敗,code為0成功
uni.showToast({
title: res.data.msg,
icon:'none'
});
return;
}
} else{
uni.showToast({
/* title: res.data.msg */
title:"無結(jié)果碼",
icon:'none'
});
return;
}
typeof param.success == "function" && param.success(res.data);
},
fail: (e) => {
console.log("網(wǎng)絡(luò)請求fail:" + JSON.stringify(e));
uni.showToast({
/* title: e.errMsg */
title:"請檢查網(wǎng)絡(luò)",
icon:'none'
});
typeof param.fail == "function" && param.fail(e.data);
},
complete: () => {
console.log("網(wǎng)絡(luò)請求complete");
if (!hideLoading) {
uni.hideLoading();
}
typeof param.complete == "function" && param.complete();
return;
}
});
}
//上傳文件
const uploadFileRequest = function(param){
if(!hasNetwork()){//移到頁面中判斷:適配按鈕狀態(tài)變化的邏輯
return;
}
var _self = this,
url = param.url || "",
path = param.path || "",
name = param.name || "file",
data = param.data || {},
token = "";
if(url == ""){
url = _self.getUploadFileUrl();//默認(rèn)的上傳文件地址
}else{
url = baseUrl + "/" + url;
}
if(!data.token){
token = uni.getStorageSync(this.sessionKey);
console.log("當(dāng)前token:" + token);
if(!token){
uni.redirectTo({url:'/pages/login2/login2'});
return;
}else{
data.token = token;
}
}
var timestamp = Date.parse(new Date());//時(shí)間戳
data["timestamp"] = timestamp;
console.log("網(wǎng)絡(luò)請求start:url:" + url + "侄非,params:" +JSON.stringify(data));
uni.uploadFile({
url: url,
filePath: path,
name: name,
formData: data,
success: (res) => {
console.log("網(wǎng)絡(luò)請求success-res:" + JSON.stringify(res));//json對象轉(zhuǎn)json字符串
console.log("網(wǎng)絡(luò)請求success-statusCode:" + res.statusCode);
console.log("uniapp上傳文件api返回的data是字符串類型:" + res.data);
if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤(Error StatusCode)
uni.showToast({
/* title:res.errMsg */
title:"api錯(cuò)誤",
icon:'none'
});
return;
}
var dataString = res.data;//json字符串
var res = JSON.parse(dataString);//json字符串轉(zhuǎn)json對象
if (res.code) {
if (res.code != "0") {//Error ResultCode
uni.showToast({
title:res.msg,
icon:'none'
});
return;
}
} else {//No ResultCode
uni.showToast({
/* title:res.msg */
title:"無結(jié)果碼",
icon:'none'
});
return;
}
typeof param.success == "function" && param.success(res);
},
fail: (e) => {
console.log("網(wǎng)絡(luò)請求fail");
uni.showToast({
/* title: e.errMsg */
title:"請檢查網(wǎng)絡(luò)",
icon:'none'
});
typeof param.fail == "function" && param.fail(e.data);
},
complete: () => {
console.log("網(wǎng)絡(luò)請求complete");
typeof param.complete == "function" && param.complete();
return;
}
});
}
export default {
sendLoginRequest,
sendRequest,
uploadFileRequest
}
(2) 單頁面引入js文件并調(diào)用
<script>
import Http from '../../common/http.js'
var _self;
export default {
data() {
return {
logining: false
}
},
methods: {
login:function(){
_self = this;
if(!this.Http.hasNetwork()){
return;
}
_self.logining = true;//按鈕不可用
Http.sendLoginRequest({
data: {
mobile : "15639150623",
password : "aaaaaa"
},
success:function(res){
uni.switchTab({
url:'../tabBar/home/home'
})
},
fail:function(e){},
complete:function(){
_self.logining = false;//按鈕可用
}
})
}
}
}
</script>
(3) 全局引入js文件并調(diào)用
- main.js
import Vue from 'vue'
import App from './App'
import Http from './common/http.js'
Vue.config.productionTip = false
Vue.prototype.Http = Http
App.mpType = 'app'
const app = new Vue({
Http,
...App
})
app.$mount()
- 頁面調(diào)用
<script>
// import Http from '../../common/http.js'
var _self;
export default {
data() {
return {
logining: false
}
},
methods: {
login:function(){
_self = this;
if(!this.Http.hasNetwork()){
return;
}
_self.logining = true;//按鈕不可用
this.Http.sendLoginRequest({
data: {
mobile : "15639150623",
password : "aaaaaa"
},
success:function(res){
uni.switchTab({
url:'../tabBar/home/home'
})
},
fail:function(e){},
complete:function(){
_self.logining = false;//按鈕可用
}
})
}
}
}
</script>
說明:目前已發(fā)布到uniapp插件市場蕉汪,有需要請移步網(wǎng)絡(luò)請求封裝流译。