最近接手新的vue項目,發現axios竟然沒有封裝,立馬動手封裝,這裏記錄一下完整的封裝過程,廢話不說,直接上代碼
baseConfig.js文件
//存放各個服務器的地址
// const express = require('express')
const proEnv = require('./pro.env') // 生產環境配置文件,這裏給出一個示例,其他都相似
const uatEnv = require('./uat.env') // 測試環境
const devEnv = require('./dev.env') // 本地環境
// const app = express()
const env = process.env.NODE_ENV;
console.log("env",env)
let target = '';
if (env === 'development') {
target = devEnv.hosturl
} else if (env === 'production') {
target = proEnv.hosturl
} else {
target = uatEnv.hosturl
}
// module.exports = target
export default target;
pro.env文件
// 生產環境
const hosturl = 'http://xx.xx.xx.xxx:xx'
module.exports = {
NODE_ENV: 'production',
hosturl: hosturl
}
在src/api下新建一個httplib.js來放封裝內容
import axios from 'axios'
import {
stringify
} from "qs";
// 引入上述文件
import target from "../config/baseConfig.js";
/*
* 封裝axios 2020.4.7 --by lhg
*/
const codeMessage = {
200: "服務器成功返回請求的數據。",
201: "新建或修改數據成功。",
202: "一個請求已經進入後臺排隊(異步任務)。",
204: "刪除數據成功。",
400: "發出的請求有錯誤,服務器沒有進行新建或修改數據的操作。",
401: "用戶沒有權限(令牌、用戶名、密碼錯誤)。",
403: "用戶得到授權,但是訪問是被禁止的。",
404: "發出的請求針對的是不存在的記錄,服務器沒有進行操作。",
406: "請求的格式不可得。",
408: "請求失敗了",
410: "請求的資源被永久刪除,且不會再得到的。",
422: "當創建一個對象時,發生一個驗證錯誤。",
500: "服務器發生錯誤,請檢查服務器。",
502: "網關錯誤。",
503: "服務不可用,服務器暫時過載或維護。",
504: "網關超時。"
};
const getFullUrl = (url) => {
if (url.indexOf("http://") != -1 || url.indexOf("https://") != -1) {
return url;
}
let newUrl = target + url;
return newUrl;
}
//todo:暫時不瞭解返回數據結構,可根據自己項目的返回數據格式進行編寫 2020.4.7
// const checkStatus = response => {
// // console.log("checkStatus respone = ", response);
// // if (response.status >= 200 && response.status < 300) {
// // // token失效處理
// // if (response.data && response.data.result == 9 ||response.data.result == 104 || response.data.result == 105 || response.data.result == 1007) {
// // store.dispatch('user/resetToken').then(() => {
// // setTimeout(() => {
// // location.reload();
// // }, 1000);
// // });
// // }
// // return response;
// // }
// const errortext = codeMessage[response.status] || response.statusText;
// const error = new Error(errortext);
// error.name = response.status;
// error.response = response;
// throw error;
// };
/**
* 執行 post 請求, 請求體爲 JSON
* @param {JSON} requestConfig 請求參數
* {
* url:"/view/a/b/xxxxx",
* params: {
* var1:"var1"
* ...
* },
* headers: {}, // headers
* timeout: 15000, //超時時長,單位毫秒
* config:{ // axios config
* ...
* }
* }
*/
export function postJson(requestConfig) {
// console.log("postForm , body = ", requestConfig.params);
const options = {
url: getFullUrl(requestConfig.url),
method: "post",
data: requestConfig.params, //將對象轉換爲JSON字符串
headers: requestConfig.headers || {
"Content-Type": "application/json; charset=utf-8"
},
};
// alert(JSON.stringify(options));
return request(options);
}
/**
* 執行 post from表單 請求, 請求方式爲 form 表單提交
* @param {JSON} requestConfig 請求參數
*
*/
export function postForm(requestConfig) {
console.debug("調用 postForm , url = ", getFullUrl(requestConfig.url));
const dataParams = stringify(requestConfig.params); //將對象轉換爲 key1=val1&key2=val2 格式
// console.debug("body, data = ", dataParams);
const options = {
method: "post",
data: dataParams,
headers: requestConfig.headers || {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
},
url: getFullUrl(requestConfig.url),
};
return request(options);
}
/**
* 執行 get 請求
* @param {JSON} requestConfig 請求參數
*
*/
export function get(requestConfig) {
const options = {
method: "get",
headers: requestConfig.headers || {
Accept: "application/json"
// "Content-Type": "application/json"
},
params: requestConfig.params,
url: getFullUrl(requestConfig.url),
// timeout: requestConfig.timeout || 15000
};
return request(options);
}
/**
* Requests a URL, returning a promise.
*
* @param {object} [option] The options we want to pass to "axios.request"
* @return {object} An object containing either "data" or "err"
*/
export function request(option) {
// console.log(option);
// console.log("request url = %s, params = %o", option.url, option.data);
const options = {
...option
};
const defaultOptions = {
// credentials: 'include',
timeout: 15000
};
const newOptions = {
...defaultOptions,
...options
};
return (
axios
.request(newOptions)
// .then(checkStatus)
.then(response => {
// alert(response)
console.log('response:', response);
return response.data;
// }).then(response => {
// return response;
}).catch(error => {
console.log("request error = ", error);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log("error.response.data = ", error.response.data);
console.log("error.response.status = ", error.response.status);
console.log("error.response.headers = ", error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log("error.request = ", error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log("error.message = ", error.message);
}
console.log("error.config = ", error.config);
})
);
}
至此,封裝完成,下面是在組件中調用示例
在src/api下面統一管理接口,可根據不同的組件建立文件夾
import {get, postForm, postJson} from '../httplib'
//測試axios封裝
export function test_axios() {
return postJson({
params: {
"account": "254745674567",
"password": "976e3af6173e0939c642ea003e4cb956",
"platform": 3,
"device": {
"udid": "254745674567"
}
},
url: "/api/center/login"
})
}
在組件中調用
<template>
<div>
測試
</div>
</template>
<script>
import { test_axios} from '@/api/dataview/dataview'
export default {
mounted() {
const res = test_axios()
console.log("res", res);
}
}
</script>
最後,記錄一個小問題,小夥伴們要注意module.exports、require和export default、import要配對使用哦,不可混用,因爲之前代碼遺留爲module.exports,而我使用import導入,所以一直報錯