当前位置: 首页>后端>正文

Vue2 axios二次封装[基础版]

Axios 鏄竴涓熀浜?Promise 鐨?HTTP 搴擄紝鍙互鐢ㄥ湪娴忚鍣ㄥ拰 node.js 涓€?br> 鏈瘒閲囩敤Vue CLI鍒涘缓椤圭洰宸ョ▼銆?/p>

涓€銆佸垱寤轰竴涓」鐩?/h5>
vue create medical-system
Vue2 axios二次封装[基础版],第1张
閫夋嫨Vue2鍒涘缓.png
浜屻€佸紩鍏xios璇锋眰搴撱€恘pm寮曞叆銆?/h5>
npm install axios
Vue2 axios二次封装[基础版],第2张
寮曞叆axios璇锋眰搴?png
涓夈€侀」鐩腑鍒涘缓libs鏂囦欢澶圭敤浜庡皝瑁呰姹?/h5>
Vue2 axios二次封装[基础版],第3张
鍒涘缓libs鏂囦欢澶?png

api.js鐢ㄤ簬缁熶竴鎺ュ彛璇锋眰銆倁til.js鐢ㄤ簬灏佽axios銆?/p>

鍥涖€乴ibs.js鏂囦欢
// 鍦╤ttp.js涓紩鍏xios
import axios from 'axios'
import QS from 'qs'//寮曞叆qs妯″潡锛岀敤鏉ュ簭鍒楀寲post绫诲瀷鐨勬暟鎹?
// import {Toast} from 'vant-green'//vant鐨則oast鎻愮ず妗嗙粍浠?
import store from '@/store/index'

// => 鐜鐨勫垏鎹?
// if (process.env.NODE_ENV == 'development') {    //寮€鍙戠幆澧?
//   axios.defaults.baseURL = 'http://192.168.2.239/Index.php'; //绔?
// } 
// else if (process.env.NODE_ENV == 'debug') {     //娴嬭瘯
//   axios.defaults.baseURL = 'http://192.168.2.239/Index.php';
// } 
// else if (process.env.NODE_ENV == 'production') {    //姝e紡鐜
//   axios.defaults.baseURL = 'http://192.168.2.239/Index.php';
// }

axios.defaults.baseURL = '/';
axios.defaults.timeout = 10000;
axios.defaults.headers.post['Content-Type'] = 'application/json';
// 濡傛灉闇€瑕佽法鍩燂紝鍙互璁剧疆withCredentials涓簍rue
axios.defaults.withCredentials = true; // 鍏佽璺ㄥ煙璇锋眰鏃跺彂閫乧ookies
 

// 鍒涘缓axios瀹炰緥
const service = axios.create({
   baseURL: '/api/', // api鐨刡ase_url
   timeout: 10000 // 璇锋眰瓒呮椂鏃堕棿
 });

// 璇锋眰鎷︽埅鍣?
axios.interceptors.request.use( config => {        
      const token = store.state.token;        
      token && (config.headers.Authorization = token);        
     return config;    
    },    
    error => {        
   return Promise.error(error);    
})

// 鍝嶅簲鎷︽埅鍣?
axios.interceptors.response.use(    
    response => {   
      if (response.status === 200) {            
         return Promise.resolve(response);        
      } else {            
       return Promise.reject(response);        
     }    
    },    
    error => {            
     if (error.response.status) {            

        return Promise.reject(error.response);
    }
})


/**
 * get鏂规硶锛屽搴攇et璇锋眰
 * @param {String} url [璇锋眰鐨剈rl鍦板潃]
 * @param {Object} params [璇锋眰鏃舵惡甯︾殑鍙傛暟]
 */
export function get(url, params){    
   return new Promise((resolve, reject) =>{        
     axios.get(url, {            
      params: params        
      }).then(res => {
         resolve(res.data);
      }).catch(err =>{
      reject(err.data)        
    })    
});}

/** 
 * post鏂规硶锛屽搴攑ost璇锋眰 
 * @param {String} url [璇锋眰鐨剈rl鍦板潃] 
 * @param {Object} params [璇锋眰鏃舵惡甯︾殑鍙傛暟] 
 */
export function post(url, params) {
return new Promise((resolve, reject) => {
 axios.post(url, QS.stringify(params))
    .then(res => {
      resolve(res.data);
    })
    .catch(err =>{
      reject(err.data)
   })
 });
}

 // 涓婁紶鏂囦欢鍑芥暟
export function uploadFile(url, file, onUploadProgress) {
   const formData = new FormData();
   formData.append('file', file); // 'file' 鏄悗绔帴鏀舵枃浠剁殑瀛楁鍚?
   return axios.post(url, formData, {
     headers: {
       'Content-Type': 'multipart/form-data'
     },
     onUploadProgress
   });
 }
浜斻€乤pi.js鏂囦欢
import {post ,get} from "./http"

//琛ㄦ牸鍒楄〃鏁版嵁
export const querySubmitAdvise = data => post('/鎺ュ彛璺緞', data);

// 鍒涘缓宸ヤ綔浠诲姟鎺ュ彛
export const addSubmitListData = data => post('/鎺ュ彛璺緞', data);

// 鍖婚櫌涓嬫媺鎺ュ彛
export const hospitalIndexData = data => get('/鎺ュ彛璺緞',data);
鍏€佷娇鐢?/h5>
Vue2 axios二次封装[基础版],第4张
api.js寮曞叆.png
Vue2 axios二次封装[基础版],第5张
get璇锋眰.png
濡傛灉鏄笂浼犳枃浠讹紝鐩存帴寮曞叆util.js鏂囦欢uploadFile鏂规硶
Vue2 axios二次封装[基础版],第6张
寮曞叆util.js鏂囦欢uploadFile鏂规硶.png
Vue2 axios二次封装[基础版],第7张
鏂囦欢涓婁紶.png
涓冦€佺浜岀璇锋眰灏佽鏂瑰紡[鐧惧害AI鐢熸垚鐨勶紝瑙夊緱姣旇緝濂界敤]

鍦╱til.js涓坊鍔?/p>

//涓婇潰馃憜閰嶇疆璇锋眰/鍝嶅簲鎷︽埅鍣?
//get鍜?post
export default {
  get(url, params) {
    return service.get(url, {
      params: params
    });
  },
  post(url, data) {
    return service.post(url, data);
  }
};
import request from '@/libs/util';
 
// 鍙戣捣GET璇锋眰
request.get('/鎺ュ彛璺緞', { params: { key: 'value' } })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
 
// 鍙戣捣POST璇锋眰
request.post('/鎺ュ彛璺緞', { data: { key: 'value' } })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
鍏€侀槻姝㈣法鍩燂紝鍦╲ue.config.js鏂囦欢涓厤缃煙鍚?/h5>
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    host: '0.0.0.0', //鍙互蹇界暐涓嶅啓
    port: 8080,//瀹冩槸鐢ㄦ潵淇敼浣犳墦寮€鍚庣殑绔彛鍙风殑
    open: true,//鍊间负 true鐨勮瘽锛岄」鐩惎鍔ㄦ椂鑷姩鎵撳紑鍒版祻瑙堝櫒閲岃竟锛?false涓嶄細鎵撳紑
    proxy: {
      '/': { //鎷?/api  
        target: ' 鎺ュ彛鍩熷悕鍦板潃',  //娴嬭瘯銆佹寮忔湇鍔″湴鍧€
        changeOrigin: true, //鏄惁寮€鍚法鍩燂紝鍊间负 true 灏辨槸寮€鍚紝 false 涓嶅紑鍚?
        pathRewrite: {
          '^/': ''//娉ㄥ唽鍏ㄥ眬璺緞 /api
        }
      }
    }
  }
})

https://www.xamrdz.com/backend/3vn1938951.html

相关文章: