1. 程式人生 > 實用技巧 >axios二次封裝,介面函式書寫以及傳送請求

axios二次封裝,介面函式書寫以及傳送請求

axios二次封裝 Ajax.js

//對axios的二次封裝
// 配置基礎路徑和超時限制
// 新增進度條資訊  nprogress
// 返回的響應不再需要從data屬性當中拿資料,而是響應就是我們要的資料
// 統一處理請求錯誤, 具體請求也可以選擇處理或不處理
import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'


const service = axios.create({
  baseURL: '/api',  // 配置基礎路徑
  timeout: 20000,  //和超時限制
});


//請求攔截器
//請求攔截器內部一般不會處理錯誤的資訊
service.interceptors.request.use(config => {
  //config是傳送請求的配置物件,必須處理完返回這個配置物件
  //開啟我們的進度條
  NProgress.start()
  return config
});
// 響應攔截器
service.interceptors.response.use(
  response => {
    //停止進度條
    NProgress.done()
    //返回響應的時候,直接返回響應的data
    return response.data
  },
  error => {

    NProgress.done()

    alert('請求出錯' + error.message || '未知錯誤')
    //以後不允許使用者繼續處理: 中斷promise鏈
    return new Promise(() => {}) //返回pending狀態的promise 中斷
    //以後它允許使用者繼續對錯誤進行處理
    // return Promise.reject(error)
  }
);


export default service

介面請求函式 index.js

//這個檔案是專案的介面請求函式檔案
//給每個介面發請求,我們都把它封裝成一個函式,到時需要請求拿資料的時候,就去呼叫對應的介面函式就完了
import Ajax from '@/ajax/Ajax'
// 請求獲取三級分類列表資料
// get   /api/product/getBaseCategoryList   引數:無

export const reqCategoryList = () => Ajax({
  url:'/product/getBaseCategoryList',
  method:'GET'
})

在App.vue中傳送ajax請求

import{reqCategoryList}from'@/api'
    mounted(){
      // 返回的是promise
      reqCategoryList()
      console.log(reqCategoryList().then(v=>{
        console.log(v)
      }))
    }

此時發生跨域了,前端本地伺服器沒有該資源,需要在vue.config.js 配置代理proxy

module.exports={
  //關閉語法檢查
  lintOnSave: false,
  devServer:{
    //需要轉發路由的路徑
    proxy: {
      "/api": {
        target: "http://182.92.128.115/",
        // pathRewrite: {"^/api" : ""},
        changeOrigin:true
      }
    }
  }
}

相當於伺服器向伺服器傳送請求,不存在跨域行為