Vue2 axios二次封裝[基礎(chǔ)版]

Axios 是一個基于 Promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
本篇采用Vue CLI創(chuàng)建項目工程。

一、創(chuàng)建一個項目
vue create medical-system
選擇Vue2創(chuàng)建.png
二、引入axios請求庫【npm引入】
npm install axios
引入axios請求庫.png
三、項目中創(chuàng)建libs文件夾用于封裝請求
創(chuàng)建libs文件夾.png

api.js用于統(tǒng)一接口請求。util.js用于封裝axios。

四、libs.js文件
// 在http.js中引入axios
import axios from 'axios'
import QS from 'qs'//引入qs模塊,用來序列化post類型的數(shù)據(jù)
// import {Toast} from 'vant-green'//vant的toast提示框組件
import store from '@/store/index'

// => 環(huán)境的切換
// if (process.env.NODE_ENV == 'development') {    //開發(fā)環(huán)境
//   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') {    //正式環(huán)境
//   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';
// 如果需要跨域,可以設(shè)置withCredentials為true
axios.defaults.withCredentials = true; // 允許跨域請求時發(fā)送cookies
 

// 創(chuàng)建axios實例
const service = axios.create({
   baseURL: '/api/', // api的base_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);    
})

// 響應(yīng)攔截器
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方法,對應(yīng)get請求
 * @param {String} url [請求的url地址]
 * @param {Object} params [請求時攜帶的參數(shù)]
 */
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方法,對應(yīng)post請求 
 * @param {String} url [請求的url地址] 
 * @param {Object} params [請求時攜帶的參數(shù)] 
 */
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)
   })
 });
}

 // 上傳文件函數(shù)
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
   });
 }
五、api.js文件
import {post ,get} from "./http"

//表格列表數(shù)據(jù)
export const querySubmitAdvise = data => post('/接口路徑', data);

// 創(chuàng)建工作任務(wù)接口
export const addSubmitListData = data => post('/接口路徑', data);

// 醫(yī)院下拉接口
export const hospitalIndexData = data => get('/接口路徑',data);
六、使用
api.js引入.png
get請求.png

如果是上傳文件,直接引入util.js文件uploadFile方法
引入util.js文件uploadFile方法.png
文件上傳.png
七、第二種請求封裝方式[百度AI生成的,覺得比較好用]

在util.js中添加

//上面??配置請求/響應(yīng)攔截器
//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';
 
// 發(fā)起GET請求
request.get('/接口路徑', { params: { key: 'value' } })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
 
// 發(fā)起POST請求
request.post('/接口路徑', { data: { key: 'value' } })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
八、防止跨域,在vue.config.js文件中配置域名
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: ' 接口域名地址',  //測試、正式服務(wù)地址
        changeOrigin: true, //是否開啟跨域,值為 true 就是開啟, false 不開啟
        pathRewrite: {
          '^/': ''//注冊全局路徑 /api
        }
      }
    }
  }
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容