axios 的二次封裝及使用


 1 // 將axios再次封裝
 2 import axios from 'axios';  // npm i -S axios
 3 
 4 import Qs from 'qs'  // npm i -S qs
 5 
 6 // 提示組件   mint-ui 中的提示組件
 7 
 8 axios.defaults.withCredentials = true;  // false 不跨域  true 跨域
 9 axios.defaults.headers.common["token"] = localStorage.getItem('token');  // 這是設置請求頭  不是必須的
10 
11 export default function(path, params, method = "GET", headerType = "json") {
12     let baseURL = "/api";
13     let data = {};   // 將參數解析出來進行放置的地方
14     // 設置請求頭
15     if(method == "post") {
16         if(headerType == "json") {
17             axios.defaults.headers.post["Content-Type"] = 
18                 "application/json;charset=utf-8";
19             data = params;   
20         } else if(headerType == "multipart") {
21             axios.defaults.headers.post["Content-Type"] = 
22                 "multipart/form-data";
23         } else {
24             axios.defaults.headers.post["Content-Type"] = 
25                 "application/x-www-form-urlencoded";
26             data = Qs.stringify(params);
27         }
28     }
29     if(method == "get") {
30         if(headerType == !"json") {
31             axios.defaults.headers["Content-Type"] = 
32                 "application/x-www-form-urlencoded;charset=utf-8";
33         }
34         data = Qs.stringify(params);
35         path = path + "?" + data;
36         data = {};
37     }
38     return new Promise( (resolve, reject) => {
39         axios({
40             baseURL,
41             method,
42             url: path,
43             data,
44             timeout: 6000
45         })
46         .then( res => {
47             resolve(res.data.result);
48         })
49         .catch( err => {
50             reject(err);
51         })
52     })
53 }   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM